python - 有没有一种简洁的方法来生成这个数据框掩码?
问题描述
我有一个带有模型score
和order_amount_bucket
. 订单金额桶中有 8 个箱子,每个箱子都有不同的阈值。我想过滤框架并生成一个布尔掩码,显示哪些行通过。
我可以通过详尽列出条件来做到这一点,但我觉得必须有一种更 Pythonic 的方式来做到这一点。
到目前为止我如何完成这项工作的一个小例子(为简单起见,只有 3 个垃圾箱)。
import pandas as pd
sc = 'score'
amt = 'order_amount_bucket'
example_data = {sc:[0.5, 0.8, 0.99, 0.95, 0.8,0.8],
amt: [1, 2, 2, 2, 3, 1]}
thresholds = [0.7, 0.8, 0.9]
df = pd.DataFrame(example_data)
# the exhaustive method to create the pass mask
# is there a better way to do this part?
pass_mask = (((df[amt]==1) & (df[sc]<thresholds[0]))
|((df[amt]==2) & (df[sc]<thresholds[1]))
|((df[amt]==3) & (df[sc]<thresholds[2]))
)
pass_mask.values
>> array([ True, False, False, False, True, False])
解决方案
您可以thresholds
转换为 adict
并使用Series.map
:
d = dict(enumerate(thresholds, 1))
# d: {1: 0.7, 2: 0.8, 3: 0.9}
pass_mark = df['order_amount_bucket'].map(d) > df['score']
[出去]
print(pass_mark.values)
array([ True, False, False, False, True, False])
推荐阅读
- python - 如何获得正在运行的特定(活动)类
- python - 用于提取十进制数的正则表达式
- linux - 为什么 java 需要基础镜像才能在 docker 上运行
- amazon-web-services - 两个子域映射到一个负载均衡器 DNS - DNS 违规
- python - 通过 HTTP 发送和接收简单的 JSON 消息
- laravel - 运行 2 个 composer.json 文件
- sql - Oracle - 按时间返回记录
- python - 使用 pydicom 添加新的私有条目密钥
- angular - 如果用户创建新文档,如何使用云功能将 Firestore 数据索引到 Algolia?
- python - 使用 pip 安装软件包后找不到 rabbitmq