简体   繁体   English

如果 groupby pandas 中的条件

[英]if condition within groupby pandas

Calculate the target column where default value is 1 but it is 0 when a group within ID1 has a Yes so for example in 9 there is one value as Yes we want to keep other No as 0计算默认值为1target列,但当 ID1 中的组具有Yes时为0 ,例如在9有一个值为Yes我们希望将其他No保留为0
Given target col is expected answer给定目标 col 是预期的答案

ID1 ID2 Match target
4   A10 Yes   1
4   A20 No    0
5   A30 Yes   1
6   A50 No    1
6   A60 No    1
7   A70 Yes   1
8   A60 No    1
9   A30 Yes   1
9   A20 No    0
9   A10 No    0

You can use Series.eq for compare with GroupBy.transform and GroupBy.all for test groups with only No value:您可以使用Series.eq与比较GroupBy.transformGroupBy.all测试组只No价值:

m1 = df['Match'].eq('No').groupby(df['ID1']).transform('all')
#or test not equal Yes
m1 = df['Match'].ne('Yes').groupby(df['ID1']).transform('all')
#alternative
#m1 = ~df['ID1'].isin(df.loc[df['Match'].ne('No'), 'ID1'])
m2 = df['Match'].eq('Yes')

df['target1'] = (m1 | m2).view('i1')
print (df)
   ID1  ID2 Match  target  target1
0    4  A10   Yes       1        1
1    4  A20    No       0        0
2    5  A30   Yes       1        1
3    6  A50    No       1        1
4    6  A60    No       1        1
5    7  A70   Yes       1        1
6    8  A60    No       1        1
7    9  A30   Yes       1        1
8    9  A20    No       0        0
9    9  A10    No       0        0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM