[英]How to change the array entries with order = 'F' in numpy
我正在嘗試替換數組的某些條目。 出於兼容性原因,我必須使用 order='F'。 我正在使用的數組很大,但要重現該問題,請嘗試以下操作。
這有效:
a = numpy.array([[1, 2], [4, 5]])
a.reshape((4, 1), order = 'C')[2] = 8
a = array([[1, 2],
[8, 5]])
以下不起作用:
a = numpy.array([[1, 2], [4, 5]])
a.reshape((4, 1), order = 'F')[2] = 8
a = array([[1, 2],
[4, 5]])
有沒有解決的辦法?
對於'C'
類型數組,這將為您提供一個新的 4x1 數組,該數組引用與原始數組相同的所有元素:
a = numpy.array([[1, 2], [4, 5]])
a.reshape((4, 1), order = 'C')[2] = 8
因此,結果與這樣做相同:
a = numpy.array([[1, 2], [4, 5]])
b = a.reshape((4, 1), order = 'C')
b[2] = 8 # this line also changes a, because it references the same elements
print(a)
print(b)
結果:
[[1 2]
[8 5]]
[[1]
[4]
[8]
[5]]
然而,這並不以同樣的方式工作:
a = numpy.array([[1, 2], [4, 5]])
a.reshape((4, 1), order = 'F')[2] = 8
因為a.reshape((4, 1), order = 'F')
確實為您提供了一個重新整形的數組,但它是具有不同維度的同一數組的全新副本,因此更改它不會更改原始數組:
a = numpy.array([[1, 2], [4, 5]])
b = a.reshape((4, 1), order = 'F') # you get a copy, order 'F'
b[2] = 8 # this line does not change a, because it references different elements.
print(a)
print(b)
結果:
[[1 2]
[4 5]]
[[1]
[4]
[8]
[5]]
但是,如果您也將a
定義為F
階數組,則a
和b
可以共享它們的數據,但結果可能會出人意料地不同(這是不同排序的全部意義所在):
a = numpy.array([[1, 2], [4, 5]], order = 'F')
b = a.reshape((4, 1), order = 'F')
b[2] = 8 # this line does change a, they share their data, both order 'F'.
print(a)
print(b)
結果:
[[1 8]
[4 5]]
[[1]
[4]
[8]
[5]]
注意作為打印的結果a
!
unravel_index
是另一種以F
順序訪問平面索引的方法:
In [120]: a[np.unravel_index(2, a.shape, order='C')]
Out[120]: 4
In [121]: a[np.unravel_index(2, a.shape, order='F')]
Out[121]: 2
In [122]: a.reshape((4,1),order='C')
Out[122]:
array([[1],
[2],
[4], # <==
[5]])
In [123]: a.reshape((4,1),order='F')
Out[123]:
array([[1],
[4],
[2], # <==
[5]])
確認這允許我們設置一個值:
In [124]: a[np.unravel_index(2, a.shape, order='F')]=8
In [125]: a
Out[125]:
array([[1, 8],
[4, 5]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.