[英]How to combine two arrays to one by their indices in the result?
Suppose that I have two arrays: 假设我有两个数组:
In [41]: x = np.array([1, 4, 9])
In [42]: y = np.array([3, 5, 7, 11])
And their indices in the result array: 以及它们在结果数组中的索引:
In [43]: ix = [1, 3, 4]
In [44]: iy = [0, 2, 5, 6]
The result array should be r = array([ 3, 1, 5, 4, 9, 7, 11])
which satisfied all(r[ix] == x)
and all(r[iy] = y)
. 结果数组应该是
r = array([ 3, 1, 5, 4, 9, 7, 11])
满足all(r[ix] == x)
和all(r[iy] = y)
。 I already known the verbose solution, and I want to find a better one (may a one line solution using something like np.where
or np.select
). 我已经知道了详细的解决方案,并且我想找到一个更好的解决方案(可以使用
np.where
或np.select
类的np.where
解决方案)。
In [45]: r = np.empty(shape=len(x)+len(y))
In [46]: r[ix] = x; r[iy] = y; r
Out[46]: array([ 3., 1., 5., 4., 9., 7., 11.])
np.array([x[1] for x in sorted(zip(ix, x) + zip(iy, y)))]
但是我不知道它是否是最佳选择,或者也许numpy有进一步的优化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.