2D numpy数组中公共元素的成对计数

2024-10-04 03:26:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个shape5000、9和dtype int的numpy数组。我正在尝试创建一个shape5000、5000和dtype int的数组,其中包含每对数组中的共享元素计数

我可以使用itertools.compositions和循环来实现这一点,但是这种方法非常慢(在我的机器上需要3-4分钟),所以我正在寻找一种更有效的替代方法。如有任何建议,将不胜感激

from itertools import combinations
import numpy as np

# create random array where row don't have duplicates
data = np.random.rand(5000, 9).argsort(axis=0)
counts = np.zeros((5000, 9), dtype=int)
for i, j in combinations(range(len(data)), 2):
    counts[i, j] = len(np.intersect1d(data[i], data[j]))


Tags: 方法importnumpy元素datalennprandom
1条回答
网友
1楼 · 发布于 2024-10-04 03:26:18

让我们试试:

# sample data with 200 unique values
np.random.seed(1)
data = np.array([np.random.choice(np.arange(200), size=9, replace=False)
                 for _ in range(5000)]
               )

# identify the unique values:
uniques = np.unique(data)

# dummy for each row
a = (data[...,None] == uniques).sum(1)

# output
out = np.einsum('ij,kj->ik',a,a)

在我的系统上大约需要4.5秒

相关问题 更多 >