【问题标题】:Piping in Python like R - adding rank像 R 一样在 Python 中管道 - 增加排名
【发布时间】:2022-11-05 17:39:13
【问题描述】:

我有一个像这样的数据框:

Feature RFI
col1    1.8
col2    1.1
col3    2.1
col4    2.8
col5    0.3

如何在一行中获得以下输出?

Rank Feature RFI
3    col1    1.8
4    col2    1.1
2    col3    2.1
1    col4    2.8
5    col5    0.3

我有以下代码要排序:

df.sort_values('RFI', ascending = True)

但我想继续使用点运算符添加到这一行,以添加类似于 R 中的管道运算符的这个排名列。 我怎样才能做到这一点?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用您提供的数据框:

    import pandas as pd
    
    df = pd.DataFrame(
        {
            "Feature": ["col1", "col2", "col3", "col4", "col5"],
            "RFI": [1.8, 1.1, 2.1, 2.8, 0.3],
        }
    )
    

    这是一种方法:

    df["Rank"] = (
        df.sort_values("RFI", ascending=False)
        .reset_index(drop=True)
        .sort_values("Feature", ascending=True)
        .index
        + 1
    )
    
    print(df)
    # Output
      Feature  RFI  Rank
    0    col1  1.8     3
    1    col2  1.1     4
    2    col3  2.1     2
    3    col4  2.8     1
    4    col5  0.3     5
    

    【讨论】:

      猜你喜欢
      • 2017-03-20
      • 2017-04-02
      • 2021-05-22
      • 2013-04-27
      • 2018-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多