首页 > 解决方案 > 基于数据框中值的百分位数分配标签的 Pythonic 方法

问题描述

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

我有一个 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%

标签: pythonpandasnumpylambdapandas-groupby

解决方案


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

#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%")

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


推荐阅读