## numpy：如何实现数组中唯一值的最有效频率计数？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (25)

`numpy`/`scipy`，有没有高效率获取数组中唯一值的频率计数的方法？

```x = array( [1,1,1,2,2,2,5,25,1,1] )
y = freq_count( x )
print y

>> [[1, 5], [2,3], [5,1], [25,1]]```

### 2 个回答

http://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html

```import numpy as np
x = np.array([1,1,1,2,2,2,5,25,1,1])
y = np.bincount(x)
ii = np.nonzero(y)[0]```

```zip(ii,y[ii])
# [(1, 5), (2, 3), (5, 1), (25, 1)]```

```np.vstack((ii,y[ii])).T
# array([[ 1,  5],
[ 2,  3],
[ 5,  1],
[25,  1]])```

```import numpy as np

x = np.array([1,1,1,2,2,2,5,25,1,1])
unique, counts = np.unique(x, return_counts=True)

print np.asarray((unique, counts)).T```

``` [[ 1  5]
[ 2  3]
[ 5  1]
[25  1]]```

```In [4]: x = np.random.random_integers(0,100,1e6)

In [5]: %timeit unique, counts = np.unique(x, return_counts=True)
10 loops, best of 3: 31.5 ms per loop

In [6]: %timeit scipy.stats.itemfreq(x)
10 loops, best of 3: 170 ms per loop```