[英]Numpy: Combine several arrays based on an indices array
I have 2 arrays of different sizes m
and n
, for instance: 我有2个大小分别为
m
和n
数组,例如:
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: 我想将
x
和y
合并为大小为m+n
的数组z
,在这种情况下:
expected_z = np.asarray([300, 400, 100, 500, 200])
In details: 详细说明:
indices
is 1, so the 1st value of z
should come from y
. indices
的第一个值为1,因此z
的第一个值为y
。 Therefore 300
. 300
。 indices
is 1, so the 2nd value of z
should also come from y
. indices
的第二个值是1,因此z
的第二个值也应该来自y
。 Therefore 400
400
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: 创建一个输出数组,并使用布尔索引将
x
和y
分配到输出的正确插槽中:
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)
和:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.