获取 NumPy 数组中唯一值的频率计数
要有效确定 NumPy 数组中每个唯一值的频率,请考虑利用NumPy 的 unique 函数与 return_counts=True 结合使用。
<code class="python">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)</code>
这种方法会生成一个包含两个数组的元组:unique,它保存原始数组中存在的唯一值,counts,它指示各自的频率每个唯一值出现的次数。
例如,使用给定的输入数组执行上述代码将返回:
[(1, 5), (2, 3), (5, 1), (25, 1)]
表示值 1 出现 5 次,2 出现 3 次,5出现一次,25 出现一次。
对于大型数据集,使用 unique(return_counts=True) 比 SciPy 的 scipy.stats.itemfreq 函数具有显着的性能优势,如下面的代码片段所示:
<code class="python">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</code>
以上是如何有效地计算 NumPy 数组中唯一值的频率?的详细内容。更多信息请关注PHP中文网其他相关文章!