gpt4 book ai didi

python - bool 掩码 Groupby Any 并创建指标

转载 作者:行者123 更新时间:2023-12-01 09:16:58 25 4
gpt4 key购买 nike

我有一个以下格式的 pandas 数据框:

id,criteria_1,criteria_2,criteria_3,criteria_4,criteria_5,criteria_6
1,0,0,95,179,1,1
1,0,0,97,185,NaN,1
1,1,2,92,120,1,1
2,0,0,27,0,1,NaN
2,1,2,90,179,1,1
2,2,5,111,200,1,1
3,1,2,91,175,1,1
3,0,8,90,27,NaN,NaN
3,0,0,22,0,NaN,NaN

我有来自 Python PANDAS: GroupBy First Transform Create Indicator 的以下程序:

mask = (((df['criteria_1'] >=1.0) | (df['criteria_2'] >=2.0)) &
(df['criteria_3'] >=90.0) &
(df['criteria_4'] <=180.0) &
((df['criteria_5'].notnull()) & (df['criteria_6'].notnull())))

# reset_index() defaults to drop=False. It inserts the old index into the DF
# as a new column named 'index'.
idx = df.reset_index()[mask].groupby('id').first().reset_index(drop=True)['index']

df['flag'] = df.index.isin(idx).astype(int)

但是,现在我想选择按组满足条件的任何行,而不仅仅是第一行。它似乎不像用 .any() 或 .all() 代替 .first() 那么容易。任何故障排除提示将不胜感激!

最佳答案

您可以直接使用mask提取所有符合您条件的行:

df['flag'] = mask.astype(int)

请记住,mask 只是一个系列,它为每一行返回一个 bool 值,具体取决于是否满足所有条件。

关于python - bool 掩码 Groupby Any 并创建指标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51163527/

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