Python 中的原始数据框:
date cash hy equity
0 2003-01-31 1 3 4
1 2003-01-31 2 5 1
2 2003-01-31 1 6 3
目标:创建三个新列,对每个 Assets 类别相对于其他两个 Assets 类别进行排名。 0 = 返回率最低的 Assets 类别。 2 = 返回率最高的 Assets 类别。
date cash hy equity cash_rank hy_rank equity_rank
0 2003-01-31 1 3 4 0 1 2
1 2003-01-31 2 5 1 1 2 0
2 2003-01-31 1 6 3 0 2 1
我使用了下面的代码:
x = [2, 5, 1]
arranged = sorted(x)
sorted_list = []
for i in x:
sorted_list.append(arranged.index(i))
这将返回新的sorted_list = [1, 2, 0],这是第二行中 Assets 类别返回的顺序。
我不知道如何使用 dataframe.apply() 方法或任何其他方法将其应用于排名列。
最佳答案
您可以申请
排名
df = df.join(df.loc[:,'cash':].apply(pd.Series.rank,1).sub(1).add_suffix('_rank'))
df
Out[145]:
date cash hy equity cash_rank hy_rank equity_rank
0 2003-01-31 1 3 4 0.0 1.0 2.0
1 2003-01-31 2 5 1 1.0 2.0 0.0
2 2003-01-31 1 6 3 0.0 2.0 1.0
关于Python:创建新的数据框列,显示相对于其他列值的排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63162946/