python - 如何获得连续元素频率的排名?

标签 python pandas dataframe

我有一个名为a 的DataFrame。我想获得每一行中出现频率最高的前两个元素。 输入:

import pandas as pd
a=pd.DataFrame({'A1':['food','movie','sport'],'A2':['game','traffic','health'],
'A3':['food','health','education'],'A4':['game','travel','other'],
'A5':['social','other','sport']})

输出:

      A1       A2         A3      A4      A5
0   food     game       food    game  social
1  movie  traffic     health  travel   other
2  sport   health  education   other   sport

预期:

      top1       top2 
0   food     game    
1  health    movie    
2  sport   education

如你所见,可能一行中的某些元素出现频率相同。对于此类元素,我只选择其中一个进行排名,例如 1 行中的所有元素出现一次, 所以我只是随机选择其中两个进行排名。

希望得到帮助和感谢!

最佳答案

计数器

from collections import Counter

tops = [
    [*zip(*Counter(r).most_common(2))][0]
    for r in zip(*map(a.get, a))
]

pd.DataFrame(tops, a.index, ['top1', 'top2'])

    top1     top2
0   food     game
1  movie  traffic
2  sport   health

关于python - 如何获得连续元素频率的排名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52341463/

相关文章:

python - 试图理解 '' .join() 在列表理解中获取列表

daemontools下的Python脚本没有收到信号15

使用 DataFrame 和 dict 获得加权总和的 Pythonic 方法

python - 如何在Python中对单列进行box-cox转换

python - Df header : Insert a full year of header rows at end of month and fill non populated months with zero

python - Pandas:计算按日期分组的差异列和附加列

python - Groupby 和基于特定行值的计算

python - 如何获取 tensorflow 中卷积层的值?

python - Pandas - 执行多列转置

Python/Pandas - 从列值重新排列字符串