繁体   English   中英

高效的成对比较 - Numpy 二维数组的行

[英]Efficient pairwise comparisons - rows of Numpy 2D array

我想将 Numpy 2D 数组的每一行与所有其他行进行比较,并获得一个二进制矩阵的输出,它表示每对行的不匹配特征。

也许,对于输入:

 index col1 col2 col3 col4
   0    2    1    3    3
   1    2    3    3    4
   2    4    1    3    2

我想得到以下输出:

 index col1 col2 col3 col4  i  j
   0    0    1    0    1    0  1
   1    1    0    0    1    0  2
   2    1    1    0    1    1  2

因为 'i' 和 'j' 保存比较行的原始索引

实现这一点的最有效方法是什么?

由于“for”循环,我当前的实现时间太长:

df = pd.DataFrame([[2,1,3,3],[2,3,3,4],[4,1,3,2]],columns=['A','B','C','D']) # example of a dataset
r = df.values
rows, cols = r.shape
additional_cols = ['i', 'j'] # original df indexes
allArrays = np.empty((0, cols + len(additional_cols)))

for i in range(0, rows):
        myArray = np.not_equal(r[i, :], r[i+1:, :]).astype(np.float32)
        myArray_with_idx = np.c_[myArray, np.repeat(i, rows-1-i), np.arange(i+1, rows)] # save original df indexes
        allArrays = np.concatenate((allArrays, myArray_with_idx), axis=0)

方法 #1:这是一个带有np.triu_indices -

a = df.values
R,C = np.triu_indices(len(a),1)
out = np.concatenate((a[R] != a[C],R[:,None],C[:,None]),axis=1)

方法#2:我们还可以利用slicing和迭代填充——

a = df.values
n = a.shape[0]
N = n*(n-1)//2
idx = np.concatenate(( [0], np.arange(n-1,0,-1).cumsum() ))
start, stop = idx[:-1], idx[1:]
out = np.empty((N,a.shape[1]+2),dtype=a.dtype)
for j,i in enumerate(range(n-1)):
    s0,s1 = start[j],stop[j]
    out[s0:s1,:-2] = a[i,None] != a[i+1:]
    out[s0:s1,-2] = j
    out[s0:s1,-1] = np.arange(j+1,n)

out将是你的allArrays

暂无
暂无

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

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