【问题标题】:Calculate rank for multiple columns using loop使用循环计算多列的排名
【发布时间】:2021-06-27 06:54:07
【问题描述】:

我有如下数据,

Company rev eps profit
c1 23.5 20.5 40.5
c2 21.5 23.5 25.5
c3 40.5 32.5 20.5

我的预期输出是:

Company rev eps profit rev_rank eps_rank profit_rank
c1 23.5 20.5 40.5 2 3 1
c2 21.5 23.5 25.5 3 2 2
c3 40.5 32.5 20.5 1 1 3

我尝试了以下输出,

for i8 in list(growth_rank):
    '{}'.format(i8)+"_rank"= growth_rank[i8].rank(ascending=False)
    growth_rank.append(i8)

它说我不能分配操作员。

如何更改代码?我知道我可以简单地尝试以下代码,而不是循环,

growth_rank['rev_rank'] = growth_rank['rev'].rank(ascending=False)

但是如何遍历数据并使用循环相应地分配/创建新的排名列?

谢谢

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用f-strings 分配所有列而不首先通过索引[1:] 选择:

    for i8 in growth_rank.columns[1:]:
        growth_rank[f"{i8}_rank"]= growth_rank[i8].rank(ascending=False).astype(int)
    print (growth_rank)
      Company   rev   eps  profit  rev_rank  eps_rank  profit_rank
    0      c1  23.5  20.5    40.5         2         3            1
    1      c2  21.5  23.5    25.5         3         2            2
    2      c3  40.5  32.5    20.5         1         1            3
    

    或处理所有列而不首先由DataFrame.iloc 选择并使用DataFrame.join 附加到原始列:

    df1 = growth_rank.iloc[:, 1:].rank(ascending=False).astype(int).add_suffix('_rank')
    df = growth_rank.join(df1)
    print (df)
      Company   rev   eps  profit  rev_rank  eps_rank  profit_rank
    0      c1  23.5  20.5    40.5         2         3            1
    1      c2  21.5  23.5    25.5         3         2            2
    2      c3  40.5  32.5    20.5         1         1            3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多