Python:创建新的数据框列,显示相对于其他列值的排名

标签 python pandas

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/

相关文章:

python - 如何获得两个 24 小时时间之间的差异?

python - 如何在两个 pandas 数据框之间应用函数

python - 如何解决我在求职面试中看到的这个递归问题?

python - Celery 将命令行参数传递给 Task

python - 如何将多个点映射到沿 y 轴的颜色渐变上?

python - 为 pandas 中的所有列生成列矩阵

python - Css 背景图像, Tornado 提供的图像

将数据写入csv的Python程序取决于列是否存在

python - 将 PeriodIndex 转换为 DateTimeIndex?

python - 保留分配给新数据框中的一列的值