Home > Net >  Group by and check field for each group pandas
Group by and check field for each group pandas

Time:03-01

My data:

  ne_type     ru_type du_type  pass_all
0   CDU50  MMU (MT1A)      DU         0
1     vDU  MMU (MT1A)     vDU         0
2   CDU50  MMU (MT2A)      DU         0
3   CDU50  MMU (MT2A)      DU         0
4   CDU50  MMU (MT2A)      DU         1
5     vDU  MMU (MT3A)     vDU         0

And How can I group by 2 fields ru_type and du_type and count total pass for group is 0, total of group is 4 After group by ru_type, du_type

ru_type     du_type    pass_all
MMU (MT1A)  DU         0
            vDU        0
MMU (MT2A)  DU         0
MMU (MT3A)  vDU        0

CodePudding user response:

No sure I got the logic but do you want?

df.groupby(['ru_type','du_type'])['pass_all'].all().astype(int)

output:

ru_type     du_type
MMU (MT1A)  DU         0
            vDU        0
MMU (MT2A)  DU         0
MMU (MT3A)  vDU        0

CodePudding user response:

Use GroupBy.all for test if all values are 1 per groups, working well if only 0 and 1 values:

df1 = df.groupby(['ru_type','du_type'])['pass_all'].all().astype(int).reset_index()
print (df1)
      ru_type du_type  pass_all
0  MMU (MT1A)      DU         0
1  MMU (MT1A)     vDU         0
2  MMU (MT2A)      DU         0
3  MMU (MT3A)     vDU         0

If need test not 0 values:

df2 = (df.assign(pass_all = df['pass_all'].ne(0))
         .groupby(['ru_type','du_type'])['pass_all'].all()
         .astype(int)
         .reset_index())
  • Related