学习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/