Skip to main content
 首页 » 编程设计

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

2025年05月04日13kevingrace

我有一个名为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