我必须找到从 hdf5 文件中读取的 NumPy 数组的模式。 NumPy 数组是 1d 并且包含浮点值。
my_array=f1[ds_name].value
mod_value=scipy.stats.mode(my_array)
我的数组是 1d 并且包含大约 1M 的值。我的脚本需要大约 15 分钟才能返回模式值。有什么办法可以加快速度吗?
另一个问题是为什么 scipy.stats.median(my_array)
在 mode 起作用时不起作用?
AttributeError: module 'scipy.stats' has no attribute 'median'
最佳答案
scipy.stats.mode
的实现有一个 Python 循环,用于处理具有多维数组的 axis
参数。下面的简单实现,仅适用于一维数组,速度更快:
def mode1(x):
values, counts = np.unique(x, return_counts=True)
m = counts.argmax()
return values[m], counts[m]
这是一个例子。首先,创建一个长度为 1000000 的整数数组。
In [40]: x = np.random.randint(0, 1000, size=(2, 1000000)).sum(axis=0)
In [41]: x.shape
Out[41]: (1000000,)
检查 scipy.stats.mode
和 mode1
是否给出相同的结果。
In [42]: from scipy.stats import mode
In [43]: mode(x)
Out[43]: ModeResult(mode=array([1009]), count=array([1066]))
In [44]: mode1(x)
Out[44]: (1009, 1066)
现在检查性能。
In [45]: %timeit mode(x)
2.91 s ± 18 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [46]: %timeit mode1(x)
39.6 ms ± 83.8 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
mode(x)
为 2.91 秒,mode1(x)
仅为 39.6 毫秒。
关于numpy - 获取numpy数组模式的最快方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46365859/