gpt4 book ai didi

python - 使用 pandas 组内的多个条件检查值是否存在

转载 作者:太空狗 更新时间:2023-10-30 02:52:36 26 4
gpt4 key购买 nike

以下是我的数据框的样子。 Expected_Output 是我想要的/目标列。

   Group  Value1  Value2  Expected_Output
0 1 3 9 True
1 1 7 6 True
2 1 9 7 True
3 2 3 8 False
4 2 8 5 False
5 2 7 6 False

如果任何 Value1 == 7 AND 如果任何 Value2 == 9 在给定的 Group 中,然后我想返回 True

我试了没用:

df['Expected_Output']= df.groupby('Group').Value1.isin(7) &  df.groupby('Group').Value2.isin(9)

注意:- 可以输出 True/False 或 1/0。

最佳答案

Group 列上使用 groupby,然后使用 transformlambda 函数 作为:

g = df.groupby('Group')
df['Expected'] = (g['Value1'].transform(lambda x: x.eq(7).any()))&(g['Value2'].transform(lambda x: x.eq(9).any()))

或者使用 groupbyapplymerge 使用参数 how='left' 作为:

df.merge(df.groupby('Group').apply(lambda x: x['Value1'].eq(7).any()&x['Value2'].eq(9).any()).reset_index(),how='left').rename(columns={0:'Expected_Output'})

或者使用groupbyapplymap作为:

df['Expected_Output'] = df['Group'].map(df.groupby('Group').apply(lambda x: x['Value1'].eq(7).any()&x['Value2'].eq(9).any()))

print(df)
Group Value1 Value2 Expected_Output
0 1 3 9 True
1 1 7 6 True
2 1 9 7 True
3 2 3 8 False
4 2 8 5 False
5 2 7 6 False

关于python - 使用 pandas 组内的多个条件检查值是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52680467/

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