gpt4 book ai didi

python - 如何计算 Pandas 每一行出现次数最多的次数?

转载 作者:太空宇宙 更新时间:2023-11-03 15:03:22 28 4
gpt4 key购买 nike

df = pd.DataFrame([[1,2,3,1,5],
[2,3,4,4,6],
[7,2,2,2,5],
[21,3,4,3,6]], index=[1,2,3,4], columns=list('ABCDE'))

df的结果值

    A   B   C   D   E
1 1 2 3 1 5
2 2 3 4 4 6
3 7 2 2 2 5
4 21 3 4 3 6

我怎么知道每行中哪个数字出现次数最多?

例如:

row 1: 1    appears two times
row 2: 4 appears two times
row 3: 2 appears three times

等等....

最佳答案

你可以使用 applyvalue_counts获得值和出现次数 concat加入他们:

value = df.apply(lambda x: x.value_counts().index[0], axis=1)
count = df.apply(lambda x: x.value_counts().iloc[0], axis=1)

out = pd.concat([value, count], axis=1).reset_index()

out.columns = ['row_num', 'val', 'appearing']
out['row_num'] = 'row ' + out['row_num'].astype(str) + ':'
out['appearing'] = 'appears ' + out['appearing'].astype(str) + ' times'

In [64]: out
Out[64]:
row_num val appearing
0 row 1: 1 appears 2 times
1 row 2: 4 appears 2 times
2 row 3: 2 appears 3 times
3 row 4: 3 appears 2 times

关于python - 如何计算 Pandas 每一行出现次数最多的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35497403/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com