Python - 计算相同长度列表中出现次数最多的元素

Python - Count most frequent elements in list of same length

过去几个小时我一直在寻找这个问题的答案,但没有找到我想要的答案,所以我决定在这里提问。

所以,假设我有一个长度相同的数据列表,例如;

0004000000350
0000090033313
0004000604363
040006203330b
0004000300a3a
0004000403833
00000300333a9
0004000003a30

匹配每个位置出现次数最多的字符的最有效方法是什么。

示例输出类似于;

0 0 0 4 0 0 0 0 0 3 3 3 3



编辑:感谢您的回答,给了我想要的东西! :)



编辑 2:我想我会添加到问题中,因为这可能是解决问题的最简单方法。有了建议的答案,您将如何添加总计数以及某种百分比?由于这是一个庞大的数据集,最常见的事件本身并不像我希望的那样清晰。

您开始使用 zip 来交错每个字符串中处于相同相对位置的字符。然后使用 scipy.stats.mode 获取每个元组的模式,并加入生成器表达式的结果字符串:

l = ['0004000000350', '0000090033313', '0004000604363', '040006203330b', 
     '0004000300a3a', '0004000403833', '00000300333a9', '0004000003a30']

from scipy.stats import mode
''.join(mode(i).mode[0] for i in list(zip(*l)))

输出

'0004000003333'
from collections import Counter
''.join(Counter(i).most_common(1)[0][0] for i in zip(*l))

其中 l 是您的字符串列表。

将字符串列表压缩到 "transpose" 它们以在同一个迭代器中呈现列,对它们应用 collections.Counter,并使用 most_common 方法,删除不需要的数据

data="""0004000000350
0000090033313
0004000604363
040006203330b
0004000300a3a
0004000403833
00000300333a9
0004000003a30"""

import collections

counts = [collections.Counter(x).most_common(1)[0][0] for x in zip(*data.splitlines())]

这产生:

['0', '0', '0', '4', '0', '0', '0', '0', '0', '3', '3', '3', '3']

(如果需要使用 "".join(counts) 加入字符以重新创建字符串)

如果没有导入,我会这样做:

data = [
"0004000000350",
"0000090033313",
"0004000604363",
"040006203330b",
"0004000300a3a",
"0004000403833",
"00000300333a9",
"0004000003a30",
]

# return the most common elemebt in an iterable
most_common = lambda ite: max(ite, key=ite.count)  

# print the most_common in each columns
print(map(most_common, zip(*data)))

# ['0', '0', '0', '4', '0', '0', '0', '0', '0', '3', '3', '3', '3']

由于没有人用过pandas,所以使用pandas可以轻松高效的实现

a = """0004000000350
0000090033313
0004000604363
040006203330b
0004000300a3a
0004000403833
00000300333a9
0004000003a30"""

import pandas as pd
df = pd.DataFrame([list(j) for j in a.strip().split('\n')])
result =  df.mode().to_string(header=None,index=None)
print(result)

""" output 
 0  0  0  4  0  0  0  0  0  3  3  3  3
"""