gpt4 book ai didi

python - 仅当值不是特定值时按值过滤数据帧

转载 作者:行者123 更新时间:2023-12-01 08:28:34 25 4
gpt4 key购买 nike

我想按 JSON 中接收的值过滤数据帧,如下所示:

region = request_json['region_value']
ma = request_json['ma_value']
market = request_json['market_value']
subsegment = request_json['subsegment_value']

filtered =df[
(df['Region'] == region) &
(df['MA/Segment'] == ma) &
(df['Market'] == market) &
(df['Subsegment'] == subsegment)
]

但是,如果regionmamarketsubsegment等于'All',我不想将其包含在过滤中。

例如,如果region = 'All',则代码应如下所示:

filtered =df[
(df['MA/Segment'] == ma) &
(df['Market'] == market) &
(df['Subsegment'] == subsegment)
]

我想避免多个 if 并寻求更优雅的解决方案。我欢迎任何想法。

最佳答案

您可以使用np.ological_and.reduce;即使您的列名包含空格、特殊字符等,这也会起作用:

conditions = {
'Region': region, 'MA/Segment': ma, 'Market': market, 'Subsegment': subsegment}

mask = pd.np.logical_and.reduce([
df[k] == v for k, v in conditions.items() if v != 'All'])
df[mask]
<小时/>

另一个选项是查询,但假设您的列名称符合有效的Python标识符名称,这将起作用。

query = ' and '.join([
f'{k}=={repr(v)}' for k, v in conditions.items() if v != 'All'])
df.query(query)

关于python - 仅当值不是特定值时按值过滤数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54054134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com