python - Pandas 对 DataFrame 行中的值进行排名

标签 python pandas

学习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 行中的特殊情况,其中两个值相同。

感谢建议

最佳答案

使用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

关于python - Pandas 对 DataFrame 行中的值进行排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62095526/

相关文章:

python - Pandas 数据框中所有系列的唯一值计数的总和

python - 如何将防伪状态传递给 Google 登录按钮或 javascript?

python - 告诉编译器它不知道的本地信息?

python - 当设置 parse_date = ['column name' 时,pd.read_csv 无法正确解析日期/月份字段]

python - Pandas read_fwf 没有加载文件的全部内容

python - 根据其他列的值有条件地更改系列的值

python - pandas MultiIndex 滚动平均值

Python添加到一个列表是一个键的值

python - 为什么这两个使用 %r 的输出之间的区别是 python 中的单引号和双引号

python - 为什么此 Popen 调用在 Django 2.0 中返回 "io.UnsupportedOperation: fileno"错误?