如何在循环中将新元素附加到 3D numpy 数组中?
How to append a new element into 3D numpy array in a loop?
我想尝试在循环 python 中将一个新元素添加到 3D numpy 数组中,但它不适用于插入或追加。
import numpy as np
a = np.array([[[24,24,3],[25,28,1],[13,34,1],[3,4,5]]])
a = np.insert(a,3,0,axis = 2)
print(a)
[[[24 24 3 0]
[25 28 1 0]
[13 34 1 0]
[ 3 4 5 0]]]
我不想在每个数组中插入 0,而是使用 for 循环
for i in range(4):
.......
结果应该是这样的:
[[[24 24 3 0]
[25 28 1 1]
[13 34 1 2]
[ 3 4 5 3]]]
你不能零敲碎打。想想一次连接整个列或平面的术语。阵列必须保持 'rectangular' - 没有破烂。
In [276]: a = np.array([[[24,24,3],[25,28,1],[13,34,1],[3,4,5]]])
In [277]: a.shape
Out[277]: (1, 4, 3)
In [278]: x = np.arange(4).reshape(1,4,1)
In [279]: x
Out[279]:
array([[[0],
[1],
[2],
[3]]])
In [280]: arr1 =np.concatenate((a,x), axis=2)
In [281]: arr1.shape
Out[281]: (1, 4, 4)
In [282]: arr1
Out[282]:
array([[[24, 24, 3, 0],
[25, 28, 1, 1],
[13, 34, 1, 2],
[ 3, 4, 5, 3]]])
或者
In [290]: arr2=np.zeros((1,4,4),int)
In [291]: arr2[:,:,:3]=a
...: arr2
Out[291]:
array([[[24, 24, 3, 0],
[25, 28, 1, 0],
[13, 34, 1, 0],
[ 3, 4, 5, 0]]])
In [292]: for i in range(4):
...: arr2[:,i,3]=i
...:
In [293]: arr2
Out[293]:
array([[[24, 24, 3, 0],
[25, 28, 1, 1],
[13, 34, 1, 2],
[ 3, 4, 5, 3]]])
我想尝试在循环 python 中将一个新元素添加到 3D numpy 数组中,但它不适用于插入或追加。
import numpy as np
a = np.array([[[24,24,3],[25,28,1],[13,34,1],[3,4,5]]])
a = np.insert(a,3,0,axis = 2)
print(a)
[[[24 24 3 0]
[25 28 1 0]
[13 34 1 0]
[ 3 4 5 0]]]
我不想在每个数组中插入 0,而是使用 for 循环
for i in range(4):
.......
结果应该是这样的:
[[[24 24 3 0]
[25 28 1 1]
[13 34 1 2]
[ 3 4 5 3]]]
你不能零敲碎打。想想一次连接整个列或平面的术语。阵列必须保持 'rectangular' - 没有破烂。
In [276]: a = np.array([[[24,24,3],[25,28,1],[13,34,1],[3,4,5]]])
In [277]: a.shape
Out[277]: (1, 4, 3)
In [278]: x = np.arange(4).reshape(1,4,1)
In [279]: x
Out[279]:
array([[[0],
[1],
[2],
[3]]])
In [280]: arr1 =np.concatenate((a,x), axis=2)
In [281]: arr1.shape
Out[281]: (1, 4, 4)
In [282]: arr1
Out[282]:
array([[[24, 24, 3, 0],
[25, 28, 1, 1],
[13, 34, 1, 2],
[ 3, 4, 5, 3]]])
或者
In [290]: arr2=np.zeros((1,4,4),int)
In [291]: arr2[:,:,:3]=a
...: arr2
Out[291]:
array([[[24, 24, 3, 0],
[25, 28, 1, 0],
[13, 34, 1, 0],
[ 3, 4, 5, 0]]])
In [292]: for i in range(4):
...: arr2[:,i,3]=i
...:
In [293]: arr2
Out[293]:
array([[[24, 24, 3, 0],
[25, 28, 1, 1],
[13, 34, 1, 2],
[ 3, 4, 5, 3]]])