调查numpy.unique
和numpy.bincount
。
E.g.
import numpy as np
x = (np.random.random(100) * 5).astype(np.int)
unique_vals, indicies = np.unique(x, return_inverse=True)
counts = np.bincount(indicies)
print unique_vals, counts
编辑:对不起,我误解你的问题......
一种方式来获得唯一的行是看待事物的结构数组...
在你的情况,你有二维数组布尔。所以也许这样?
import numpy as np
numrows, numcols = 10,3
x = np.random.random((numrows, numcols)) > 0.5
x = x.view(','.join(numcols * ['i1'])) # <- View the rows as a 1D structured array...
unique_vals, indicies = np.unique(x, return_inverse=True)
counts = np.bincount(indicies)
print unique_vals, counts
当然,没有什么真的错了你最初做的方式...只是展现给写你的原始功能略有更清洁的方式(使用元组,贾斯汀建议):
def unique_rows(data):
unique = dict()
for row in data:
row = tuple(row)
if row in unique:
unique[row] += 1
else:
unique[row] = 1
return unique
我们可以借此一步越走越使用defaultdict:
from collections import defaultdict
def unique_rows(data):
unique = defaultdict(int)
for row in data:
unique[tuple(row)] += 1
return unique
碰巧,这些选项似乎比做它的“numpy的-thonic”的方式更快...(我将猜对了!尽管如此,将行转换为字符串仍然很慢。你一定要比较元组而不是字符串)。
我不认为你的方式是如此糟糕,虽然我会使用行的元组作为键,而不是将行转换为字符串。也就是说,我认为乔金顿的方法非常好。 – 2010-10-13 04:19:48
我会继续介绍贾斯汀所说的话:你已经在做事情的方式没有任何问题。事实上,如果你使用贾斯汀建议的元组并直接遍历数组的行('for data in row:'),它实际上比我下面的方法快。 – 2010-10-13 16:25:11
你可以从http://stackoverflow.com/questions/16970982/find-unique-rows-in-numpy-array获得很多好的想法解决方案 – j08lue 2016-12-02 12:25:31