获取两组的唯一交集值

时间:2016-09-20 03:38:37

标签: python numpy hash intersection

我想使用哈希来获取唯一向量的索引(对于矩阵来说它是有效的)但是np.intersect1d不给出索引,它给出了值。另一方面,np.in1d确实给出了索引而不是唯一的索引。我压缩了一个字典以使它工作,但它似乎并不是最有效的。我是python的新手,所以试着看看是否有更好的方法来做到这一点。谢谢你的帮助!

代码:

=SUMIF(Sheet1!$B$2:$B$7,Sheet3!B2,Sheet1!$C$2:$C$7)+
 SUMIF(Sheet2!$B$2:$B$7,Sheet3!B2,Sheet2!$C$2:$C$7)

输出:

import numpy as np
import hashlib
x=np.array([[1, 2, 3],[1, 2, 3], [4, 5, 6], [7, 8, 9]])
y=np.array([[4, 5, 6], [7, 8, 9],[1, 2, 3]])

xhash=[hashlib.sha1(row).digest() for row in x]
yhash=[hashlib.sha1(row).digest() for row in y]
z=np.intersect1d(xhash,yhash)

idx=list(range(len(xhash)))

d=dict(zip(xhash,idx))
unique_idx=[d[i] for i in z] #is there a better way to get this or boolean array
print(unique_idx)
uniques=np.array([x[i] for i in unique_idx])
print(uniques)

我对np.unique()有类似的问题,它没有给我任何索引。

2 个答案:

答案 0 :(得分:0)

numpy_indexed包(免责声明:我是它的作者)具有执行此类操作(及相关功能)的高效功能:

import numpy_indexed as npi
uniques = npi.intersection(x, y)

请注意,此解决方案不使用散列,而是使用序列元素的按位相等;所以不存在哈希冲突的风险,并且在实践中可能要快得多。

答案 1 :(得分:0)

使用np.unique的return_index属性返回in1d给出的唯一值的标志

代码:

import numpy as np
import hashlib
x=np.array([[1, 2, 3],[1, 2, 3], [4, 5, 6], [7, 8, 9]])
y=np.array([[1, 2, 3], [7, 8, 9]])
xhash=[hashlib.sha1(row).digest() for row in x]
yhash=[hashlib.sha1(row).digest() for row in y]
z=np.in1d(xhash,yhash)

##Use unique to get unique indices to ind1 results
_,unique=np.unique(np.array(xhash)[z],return_index=True)

##Compute indices by indexing an array of indices
idx=np.array(range(len(xhash)))
unique_idx=(np.array(idx)[z])[unique]

print('x=',x)
print('unique_idx=',unique_idx)
print('x[unique_idx]=',x[unique_idx])

输出:

x= [[1 2 3]
 [1 2 3]
 [4 5 6]
 [7 8 9]]
unique_idx= [3 0]
x[unique_idx]= [[7 8 9]
 [1 2 3]]
相关问题