首页 > 解决方案 > 有没有一种简洁的方法来生成这个数据框掩码?

问题描述

我有一个带有模型scoreorder_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])

标签: pythonpandas

解决方案


您可以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])

推荐阅读