如果groupbyPandas内的条件

2024-06-02 18:01:56 发布

您现在位置:Python中文网/ 问答频道 /正文

计算target列,其中默认值为1,但当ID1中的组具有Yes时,它是0,因此,例如在9中,有一个值为Yes,我们希望将其他No保持为0
给定的目标列是预期答案

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

Tags: no答案target目标matcha10yesid2
1条回答
网友
1楼 · 发布于 2024-06-02 18:01:56

您可以使用^{}^{}^{}比较只具有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

相关问题 更多 >