Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Numpy:基于索引数组组合多个数组_Python_Arrays_Numpy - Fatal编程技术网

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
我怎么能在NumPy有效地做到这一点


提前谢谢

我希望这能帮助您:

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抱歉,我以为你的阵列很小