python - 在非常大的数据集上在 python 中生成 n 选择 2 种组合

标签 python numpy

我需要创建 n choose 2 组合,目前正在使用 pythons itertools.combinations 模块。

对于一个包含 30,000 个字符串的列表,创建组合会运行数小时并使用大量 ram,即

list(itertools.combinations(longlist,2))

是否有一种生成组合的方法可以更好地针对内存中的大对象进行优化?或者有没有办法使用 numpy 来加速这个过程?

最佳答案

我会使用基于 np.triu_indices 的生成器
这些是 nxn 方阵的上三角矩阵的索引,其中 n = len(long_list)

问题在于首先创建了整套索引。 itertools 不会这样做,一次只生成每个组合。

def combinations_of_2(l):
    for i, j in zip(*np.triu_indices(len(l), 1)):
        yield l[i], l[j]

long_list = list('abc')
c = combinations_of_2(long_list)
list(c)

[('a', 'b'), ('a', 'c'), ('b', 'c')]

一次全部搞定

a = np.array(long_list)
i, j = np.triu_indices(len(a), 1)
np.stack([a[i], a[j]]).T

array([['a', 'b'],
       ['a', 'c'],
       ['b', 'c']], 
      dtype='<U1')

时间
long_list = pd.DataFrame(np.random.choice(list(ascii_letters), (3, 1000))).sum().tolist()
enter image description here

关于python - 在非常大的数据集上在 python 中生成 n 选择 2 种组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40617199/

相关文章:

algorithm - 如何每次不放样重新称量(条件抽样)?

Python 闭包没有按预期工作

python - 使用 LinkedBrush gridplot 在 Bokeh 中绘制多个系列

Tor 的 Python 脚本异常

python - 使用PIL用剪贴蒙版绘制渐变?

python - 如何记录 Python 交互式 shell session 中发生的一切?

python - 每次对输出 NetCDF 变量进行赋值是否都会导致整个数据集的重写?

python - 分别为每个 channel 对 3d 数组与 2d 内核进行卷积

python - NumPy 中的 cumsum 函数在添加时会衰减吗?

python - 为什么 len 在 DataFrame 上比在底层 numpy 数组上效率高得多?