【问题标题】:Pythonic way to assign labels based on percentile of values in a dataframe基于数据框中值的百分位数分配标签的 Pythonic 方法
【发布时间】:2020-11-23 01:56:07
【问题描述】:

我想知道解决我遇到的以下问题的好方法。

我有一个 python 数据框,其中包含与 ID 关联的 3 个预先计算的值。我想根据与计算列之一对应的值关联的百分位数为该 ID 分配一个标签

给定数据:

### note : VAL1 is a rank i.e lower the better
###.       VAL2 is just a number associated to the ID where the higher the number the better. Assume VAL2 min = 0, max = 25000
df = pd.DataFrame({"ID": [132, 444, 323], "VAL1": [0.82, 0.16, 0.48], "VAL2": [24000, 6242, 16824]})
    #     ID      VAL1     VAL2
    # 0   132     0.82     24000
    # 1   444     0.16     6242
    # 2   323     0.48     16824

想要的输出:

output_df = 
    #     ID      VAL1     VAL2     VAL1_LABEL     VAL2_LABEL
    # 0   132     0.82     24000    bottom50%      top25%
    # 1   444     0.16     6242     top25%         bottom50%
    # 2   323     0.48     16824    middle25-50%   middle25-50%

【问题讨论】:

  • pd.qcut(df.VAL1,[0,.25,.50,1]) ?
  • 我不知道这个功能,让我看看,但乍一看它似乎可以满足我的需求,谢谢!

标签: python pandas numpy lambda pandas-groupby


【解决方案1】:

从我在您的问题中可以看出,这与您正在寻找的内容很接近:

#take 1-the proportion to get the inverse that you want
df["VAL1_LABEL"] = 1 - df.VAL1/sum(df.VAL1)
df["VAL1_LABEL"] = np.where(df.VAL1_LABEL<df.VAL1_LABEL.mean(),"bottom50%","top50%")

您可以通过添加嵌套条件进一步指定。

【讨论】:

    【解决方案2】:

    像这样赋值

    df['VAL1_LABEL'] = pd.qcut(df.VAL1,[0,.5,.75,1], labels=['bottom25%','middle25%-50%','top25%']) 
    Out[199]: 
    0       top25%
    1    bottom25%
    2    bottom25%
    Name: VAL1, dtype: category
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-09
      • 1970-01-01
      • 2021-12-26
      • 2018-10-31
      • 1970-01-01
      相关资源
      最近更新 更多