在numpy数组上应用Counter获取列模式

问题描述 投票:0回答:2

我有3个numpy数组

import numpy as np

a=np.array([1,2,4,4])
b=np.array([1,3,4,3])
c=np.array([1,2,3,3])

我需要这样的输出

array([1,2,4,3])

其中,索引i处的值在该列中出现频率最高的元素,即。

  • 在第一列中,1出现的次数最多。
  • 在第二列中 2出现的次数最多。

以此类推...

python-3.x numpy numpy-ndarray
2个回答
1
投票

你可以使用 Counter 以如下方式。

from collections import Counter
result = []
for i,_ in enumerate(zip(a,b,c)):
  count = Counter([a[i], b[i], c[i]])
  result.append(count.most_common(1)[0][0])

result 将给 [1,2,4,3].


0
投票

如果你有scipy依赖,你可以使用内置的函数 scipy.stats.mode 沿着堆叠数组的0轴。或者,你可以使用 numpy.unique收藏品.计数器 沿着堆叠数组的列。

Scipy模式

import numpy as np
from scipy.stats import mode
from collections import Counter

a = np.array([1,2,4,4])
b = np.array([1,3,4,3])
c = np.array([1,2,3,3])

m = np.vstack([a,b,c])

mode(m, axis=0)[0]
array([[1, 2, 4, 3]])

Numpy Unique

modes_numpy = []

for c in m.T:
    vals, counts = np.unique(c, return_counts=True)
    index = np.argmax(counts)
    modes_numpy.append(vals[index])

modes_numpy
[1, 2, 4, 3]

收款柜台

modes_counter = []

for c in m.T:
    modes_counter.append(Counter(c).most_common(1)[0][0])

modes_counter
[1, 2, 4, 3]
© www.soinside.com 2019 - 2024. All rights reserved.