NumPy配列内の一意の値の頻度カウント 質問する

NumPy配列内の一意の値の頻度カウント 質問する

NumPy 配列内の各一意の値の頻度カウントを効率的に取得するにはどうすればよいですか?

>>> x = np.array([1,1,1,2,2,2,5,25,1,1])
>>> freq_count(x)
[(1, 5), (2, 3), (5, 1), (25, 1)]

ベストアンサー1

使用numpy.unique(NumPy 1.9+の場合return_counts=True):

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]]

と比較してscipy.stats.itemfreq:

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

おすすめ記事