简体   繁体   English

numpy:根据索引数组组合多个数组

[英]Numpy: Combine several arrays based on an indices array

I have 2 arrays of different sizes m and n , for instance: 我有2个大小分别为mn数组,例如:

x = np.asarray([100, 200])
y = np.asarray([300, 400, 500])

I also have an integer array of size m+n , for instance: 我也有一个大小为m+n的整数数组,例如:

indices = np.asarray([1, 1, 0, 1 , 0])

I'd like to combine x and y into an array z of size m+n , in this case: 我想将xy合并为大小为m+n的数组z ,在这种情况下:

expected_z = np.asarray([300, 400, 100, 500, 200])

In details: 详细说明:

  • The 1st value of indices is 1, so the 1st value of z should come from y . indices的第一个值为1,因此z的第一个值为y Therefore 300 . 因此300
  • The 2nd value of indices is 1, so the 2nd value of z should also come from y . indices的第二个值是1,因此z的第二个值也应该来自y Therefore 400 因此400
  • The 3rd value of indices is 0, so the 3rd value of z should this time come from x . indices的第三值是0,因此这次z的第三值应该来自x Therefore 100 因此100
  • ... ...

How could I do that efficiently in NumPy? 我如何在NumPy中有效地做到这一点?

Thanks in advance! 提前致谢!

Make an output array and use boolean indexing to assign x and y into the correct slots of the output: 创建一个输出数组,并使用布尔索引将xy分配到输出的正确插槽中:

z = numpy.empty(len(x)+len(y), dtype=x.dtype)
z[indices==0] = x
z[indices==1] = y

out will be your desired output: out将是您想要的输出:

out = indices.copy()
out[np.where(indices==0)[0]] = x
out[np.where(indices==1)[0]] = y

or as the above answer suggested, simply do: 或按照上述答案建议,只需执行以下操作:

out = indices.copy()
out[indices==0] = x
out[indices==1] = y

i hope this could help you: 我希望这可以帮助您:

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

and the output is: 输出为:

output : array([300., 400., 100., 500., 200.])

PS always make sure that len(indices) == len(x) + len(y) and : PS始终确保len(indices) == len(x) + len(y)和:

  • the values that are coming from y == len(y) 来自y的值== len(y)
  • the values that are coming from x == len(x) 来自x的值== len(x)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM