Python Numpy:基于索引数组组合多个数组
我有两个大小不同的数组,例如:Python Numpy:基于索引数组组合多个数组,python,arrays,numpy,Python,Arrays,Numpy,我有两个大小不同的数组,例如: x = np.asarray([100, 200]) y = np.asarray([300, 400, 500]) 我还有一个大小为m+n的整数数组,例如: x = np.asarray([100, 200]) y = np.asarray([300, 400, 500]) index=np.asarray([1,1,0,1,0]) 我想将x和y组合成一个大小为m+n的数组z,在这种情况下: expected_z=np.asarray([300400100
x = np.asarray([100, 200])
y = np.asarray([300, 400, 500])
我还有一个大小为m+n
的整数数组,例如:
x = np.asarray([100, 200])
y = np.asarray([300, 400, 500])
index=np.asarray([1,1,0,1,0])
我想将x
和y
组合成一个大小为m+n
的数组z
,在这种情况下:
expected_z=np.asarray([300400100500200])
详情如下:
索引的第一个值是1,因此
的第一个值应该来自z
。因此y
300
索引的第二个值是1,因此
的第二个值也应该来自z
。因此y
400
索引的第三个值是0,因此
的第三个值应该来自z
。因此x
100
提前谢谢 我希望这能帮助您:
x = np.asarray([100, 200])
y = np.asarray([300, 400, 500])
indices = np.asarray([1, 1, 0, 1 , 0])
expected_z = np.asarray([])
x_indice = 0
y_indice = 0
for i in range(0,len(indices)):
if indices[i] == 0:
expected_z = np.insert(expected_z,i,x[x_indice])
x_indice += 1
else:
expected_z = np.insert(expected_z,i,y[y_indice])
y_indice += 1
expected_z
输出为:
output : array([300., 400., 100., 500., 200.])
请务必确保len(索引)==len(x)+len(y)
和:
- 来自y==len(y)的值
- 来自x==len(x)的值
x
和y
分配到输出的正确插槽中:
z = numpy.empty(len(x)+len(y), dtype=x.dtype)
z[indices==0] = x
z[indices==1] = y
out
将是您所需的输出:
out = indices.copy()
out[np.where(indices==0)[0]] = x
out[np.where(indices==1)[0]] = y
或者,正如上面的答案所建议的,只需执行以下操作:
out = indices.copy()
out[indices==0] = x
out[indices==1] = y
这需要二次时间,并产生一个数据类型错误的输出数组。感谢Mehdi的回复。如果阵列很大,我担心在阵列上循环会非常低效…@FlorianPagnoux抱歉,我以为你的阵列很小