获取 numpy 中唯一行的位置的更快方法是什么

2024-02-20

我有一个唯一行的列表和另一个更大的数据数组(在示例中称为 test_rows)。我想知道是否有一种更快的方法来获取数据中每个唯一行的位置。我能想到的最快的方法是......

import numpy


uniq_rows = numpy.array([[0, 1, 0],
                         [1, 1, 0],
                         [1, 1, 1],
                         [0, 1, 1]])

test_rows = numpy.array([[0, 1, 1],
                         [0, 1, 0],
                         [0, 0, 0],
                         [1, 1, 0],
                         [0, 1, 0],
                         [0, 1, 1],
                         [0, 1, 1],
                         [1, 1, 1],
                         [1, 1, 0],
                         [1, 1, 1],
                         [0, 1, 0],
                         [0, 0, 0],
                         [1, 1, 0]])

# this gives me the indexes of each group of unique rows
for row in uniq_rows.tolist():
    print row, numpy.where((test_rows == row).all(axis=1))[0]

这打印...

[0, 1, 0] [ 1  4 10]
[1, 1, 0] [ 3  8 12]
[1, 1, 1] [7 9]
[0, 1, 1] [0 5 6]

有没有更好或更numpythonic(不确定这个词是否存在)的方法来做到这一点?我正在寻找 numpy group 函数但找不到它。基本上,对于任何传入的数据集,我需要最快的方法来获取该数据集中每个唯一行的位置。传入的数据集并不总是具有每个唯一的行或相同的数字。

编辑: 这只是一个简单的例子。在我的应用程序中,数字不仅仅是 0 和 1,它们可以是 0 到 32000 之间的任意值。 uniq 行的大小可以在 4 到 128 行之间,而 test_rows 的大小可以是数十万行。


Numpy

从 numpy 1.13 版本开始,您可以使用numpy.unique https://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html like np.unique(test_rows, return_counts=True, return_index=True, axis=1)

Pandas

df = pd.DataFrame(test_rows)
uniq = pd.DataFrame(uniq_rows)

uniq

    0   1   2
0   0   1   0
1   1   1   0
2   1   1   1
3   0   1   1

或者您可以从传入的 DataFrame 自动生成唯一的行

uniq_generated = df.drop_duplicates().reset_index(drop=True)

yields

    0   1   2
0   0   1   1
1   0   1   0
2   0   0   0
3   1   1   0
4   1   1   1

然后寻找它

d = dict()
for idx, row in uniq.iterrows():
    d[idx] = df.index[(df == row).all(axis=1)].values

这和你的差不多where method

d

{0: array([ 1,  4, 10], dtype=int64),
 1: array([ 3,  8, 12], dtype=int64),
 2: array([7, 9], dtype=int64),
 3: array([0, 5, 6], dtype=int64)}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

获取 numpy 中唯一行的位置的更快方法是什么 的相关文章

随机推荐