本文探讨了一种计算 NumPy 数组中唯一值的频率计数的有效方法。
使用 numpy.unique 且 return_counts=True (对于 NumPy版本 1.9 及更高版本)允许有效计算唯一值及其相应的计数。举例说明:
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)
此方法在执行速度方面显着优于 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
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3