![](/img/trans.png)
[英]Numpy: Efficient elements of array A in terms of the indices of matching elements of array B
[英]Matching elements in numpy array
我有两个numpy数组。 第一个Z1大约长30万行,宽3列。 第二个Z2大约为200,000行300列。 Z1和Z2的每一行都有一个标识号(10位数字)。 Z2包含Z1中项目的子集,我想基于10位标识号将Z2中的行与其Z1中的伙伴进行匹配,然后从Z1中提取第2列和第3列,并将它们插入到Z2中的末尾他们适当的行。
Z1和Z2都没有任何特定顺序。
我想到的唯一方法是遍历数组,这需要几个小时。 在Python中有更好的方法吗?
谢谢!
我从您的问题中了解到10位标识符存储在第1列中,对吗?
这是不是很容易做到,很多间接的事情,但最终unsorted_insert
拥有其中的行号Z1
的每个标识符Z2
是
sort_idx = np.argsort(Z1[:, 0])
sorted_insert = np.searchsorted(Z1[:, 0], Z2[:, 0], sorter=sort_idx)
# The following is equivalent to unsorted_insert = sort_idx[sorted_insert] but faster
unsorted_insert = np.take(sort_idx, sorted_insert)
因此,现在我们要做的就是获取这些行的最后两列,并将它们堆叠到Z2
数组中:
new_Z2 = np.hstack((Z2, Z1[unsorted_insert, 1:]))
一个没有问题的完整示例:
import numpy as np
z1_rows, z1_cols = 300000, 3
z2_rows, z2_cols = 200000, 300
z1 = np.arange(z1_rows*z1_cols).reshape(z1_rows, z1_cols)
z2 = np.random.randint(10000, size=(z2_rows, z2_cols))
z2[:, 0] = z1[np.random.randint(z1_rows, size=(z2_rows,)), 0]
sort_idx = np.argsort(z1[:, 0])
sorted_insert = np.searchsorted(z1[:, 0], z2[:, 0], sorter=sort_idx)
# The following is equivalent to unsorted_insert = sort_idx[sorted_insert] but faster
unsorted_insert = np.take(sort_idx, sorted_insert)
new_z2 = np.hstack((z2, z1[unsorted_insert, 1:]))
尚未计时,但整个过程似乎在几秒钟内完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.