python - 基于数据框中值的百分位数分配标签的 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%
解决方案
从我在您的问题中可以看出,这与您正在寻找的内容很接近:
#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%")
您可以通过添加嵌套条件进一步指定。
推荐阅读
- regex - 反转括号内的两个字符串
- swift - 地理围栏 didExitRegion 从未被调用
- javascript - Rxjs 链转换 observable
可观察的 (base64) - phpmyadmin - 是否可以在 xampp 中有多个版本的 php
- c# - 使用 C# 在域上保留具有快照的虚拟机
- javascript - 为什么我的表单没有将 id 传递给控制器?
- c# - 从另一种形式更改一种形式的文本
- sql - MSSQL WHERE YEAR 子句返回所有日期而不是指定日期
- asp.net - 通过vb.net中的foreach循环在列表中插入类属性
- python - 用整数规划求解最小化