python - 查找每列中出现次数最多的元素的最简单方法

标签 python list matrix

假设我有

data =
[[a, a, c],
 [b, c, c],
 [c, b, b],
 [b, a, c]]

我想得到一个包含每列中出现次数最多的元素的列表:result = [b, a, c],最简单的方法是什么?

我使用 Python 2.6.6

最佳答案

在统计学中,您想要的是模式。 scipy 库 ( http://www.scipy.org/ ) 在 scipy.stats 中有一个 mode 函数。

In [32]: import numpy as np

In [33]: from scipy.stats import mode

In [34]: data = np.random.randint(1,6, size=(6,8))

In [35]: data
Out[35]: 
array([[2, 1, 5, 5, 3, 3, 1, 4],
       [5, 3, 2, 2, 5, 2, 5, 3],
       [2, 2, 5, 3, 3, 2, 1, 1],
       [2, 4, 1, 5, 4, 4, 4, 5],
       [4, 4, 5, 5, 2, 4, 4, 4],
       [2, 4, 1, 1, 3, 3, 1, 3]])

In [36]: val, count = mode(data, axis=0)

In [37]: val
Out[37]: array([[ 2.,  4.,  5.,  5.,  3.,  2.,  1.,  3.]])

In [38]: count
Out[38]: array([[ 4.,  3.,  3.,  3.,  3.,  2.,  3.,  2.]])

关于python - 查找每列中出现次数最多的元素的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15554691/

相关文章:

list - 用 Foldl 剪掉任何内容

c++ - 未排序矩阵搜索算法

python - 使用 totient 函数 - 未定义的问题

c# - 二进制序列化列表

Python:使只读属性可通过 **vars(some_class) 访问

python - 如何将索引列转换为普通列。?第 2colm 是索引并且我应用了 df_agg.index 并且我得到了我只需要 Txn_Date 中的日期的列

r - 距离矩阵计算

Matlab向量除法: I want to know how matlab divided the two vectors

python - Django:使用 Javascript 解析我的模板中的 JSON

python - 在大数据集上训练模型的最佳实践是什么