问题描述
我有一个2D阵列包含整数(两个正或负)。每行重新presents随时间的值特定空间部位,而各列重新presents值不同的空间位点的一个给定的时间。
I have a 2D array containing integers (both positive or negative). Each row represents the values over time for a particular spatial site, whereas each column represents values for various spatial sites for a given time.
因此,如果数组是这样的:
So if the array is like:
1 3 4 2 2 7
5 2 2 1 4 1
3 3 2 2 1 1
结果应该是
1 3 2 2 2 1
请注意,当有对模式的倍数的值,任何一个(随机选择的)可被设定为模式
Note that when there are multiple values for mode, any one (selected randomly) may be set as mode.
我可以遍历列找到模式一次,但我希望numpy的可能有一些内置的功能来做到这一点。或者,如果有一招地发现,没有有效的循环。
I can iterate over the columns finding mode one at a time but I was hoping numpy might have some in-built function to do that. Or if there is a trick to find that efficiently without looping.
推荐答案
检查<$c$c>scipy.stats.mode() (由@ tom10的评论启发):
Check scipy.stats.mode()
(inspired by @tom10's comment):
import numpy as np
from scipy import stats
a = np.array([[1, 3, 4, 2, 2, 7],
[5, 2, 2, 1, 4, 1],
[3, 3, 2, 2, 1, 1]])
stats.mode(a)
输出:
(array([[ 1., 3., 2., 2., 1., 1.]]),
array([[ 1., 2., 2., 2., 1., 2.]]))
这篇关于最有效的方法来查找numpy的阵列模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!