熊猫在DataFrame的行中的排名值

问题描述 投票:2回答:1

学习Python。我有一个像这样的数据框

     cand1    cand2    cand3
0    40.0900  39.6700  36.3700
1    44.2800  44.2800  35.4200
2    43.0900  51.2200  46.3500
3    35.7200  55.2700  36.4700

而且我想根据列的值对每一行进行排名,以便得到

     cand1    cand2    cand3
0    1        2        3
1    1        1        3
2    1        3        2
3    3        1        2

我现在有

    for index, row in df.iterrows():
        df.loc['Rank'] = df.loc[index].rank(ascending=False).astype(int)
        print (df)

但是,这会继续重复整个数据帧。另请注意第2行中的特殊情况,其中两个值相同。

建议表示赞赏

python pandas
1个回答
2
投票

使用df.rank代替系列rank

df_rank = df.rank(axis=1, ascending=False, method='min').astype(int)

Out[165]:
   cand1  cand2  cand3
0      1      2      3
1      1      1      3
2      3      1      2
3      3      1      2
© www.soinside.com 2019 - 2024. All rights reserved.