[英]How to iterate over a numpy array at a given axis?
我有一個形狀的ndarray
my_array = np.zeros((Na, Nb, Nc))
我有Nb束形狀數據(Na,Nc)
我想用我的數據束填充“ my_array”,如下所示:
for b, bit in zip(range(Nb), my_bits):
my_array[:, b, :] = bit
但是我想對任意形狀數據集的任意仲裁軸進行此操作。 我該怎么做?
**編輯**有人指出我的問題含糊不清。 下面是我知道如何做的示例代碼,導致了我不知道的事情。
我知道的:
my_bits = [np.ones((Na, Nc)) for j in range(Nb)]
my_array = np.zeros((Na, Nb, Nc))
for b, bit in zip(range(Nb), my_bits):
my_array[:, b, :] = bit
一般而言,我們可以考慮
my_array = np.zeros((N1, N2, ..., Nj, ..., Nmax))
bit = np.ones((N1, N2, ..., Nj-1, Nj+1, ..., Nmax))
my_bits = [bit]*Nj
從那里,我想沿軸Nj用my_bits填充my_array。 我該怎么做? 我正在查看nditer函數,但不確定如何處理。
這里的尺寸有問題。 如果我正確理解, my_array[:, 0, :]
my_bits
my_array[:, 0, :]
與my_bits
維數相同。 所以分配應該像這樣完成:
import numpy as np
Na = 2
Nb = 2
Nc = 2
my_array = np.zeros((Na, Nb, Nc))
my_bits = np.ones((Na, Nc))
print('my_array before', my_array)
for b in range(Nb):
my_array[:, b, :] = my_bits
print('my_array after', my_array)
我認為您可能想要numpy.transpose
list_of_2d_arrays = [ make_2d_array() for i in range(Nb) ] # each has shape=(Na,Nc)
tensor3d = np.array(list_of_2d_arrays) # shape = (Nb,Na,Nc)
# now shift the dimensions around
X = np.transpose(tensor3d,(1,0,2)) # has shape (Na,Nb,Nc)
在某些numpy
函數中,使用transpose
將迭代軸移動到已知位置(最前面或最后一個)。
另一種方法是構造一個slice
對象,並對其進行迭代。
In [46]: arr = np.zeros((2,3,4),int)
In [47]: idx = np.full((arr.ndim,), slice(None))
In [48]: n=2
In [49]: for i in range(arr.shape[n]):
...: idx[n] = i
...: arr[tuple(idx)] = i+1
...:
In [50]: arr
Out[50]:
array([[[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]],
[[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]]])
對於另一個軸
In [56]: arr = np.zeros((2,3,4),int)
In [57]: idx = np.full((arr.ndim,), slice(None))
In [58]: n=1
In [59]: for i in range(arr.shape[n]):
...: idx[n] = i
...: arr[tuple(idx)] = i+1
...:
In [60]: arr
Out[60]:
array([[[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3]],
[[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3]]])
在這種情況下, idx
變化如下:
[slice(None, None, None) 0 slice(None, None, None)]
[slice(None, None, None) 1 slice(None, None, None)]
[slice(None, None, None) 2 slice(None, None, None)]
關鍵是索引表達式具有等效的元組,可以通過編程方式構造它:
In [61]: np.s_[:,3,:]
Out[61]: (slice(None, None, None), 3, slice(None, None, None))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.