简体   繁体   中英

How to filter all rows that belong to groups with more than 1 member?

I have a similar question as this one .

I have a dataframe like this:

import pandas as pd

df = pd.DataFrame({'A': list(range(7)),
                   'B': ['a', 'b', 'a', 'c', 'c', 'b', 'b'],
                   'C': ['x', 'x', 'x', 'z', 'z', 'y', 'x']}
                  )

   A  B  C
0  0  a  x
1  1  b  x
2  2  a  x
3  3  c  z
4  4  c  z
5  5  b  y
6  6  b  x

I want to groupby columns B and C and then select all rows from df that have a group size greater than 1.

My desired outcome would be

   A  B  C
0  0  a  x
1  1  b  x
2  2  a  x
3  3  c  z
4  4  c  z
6  6  b  x

So I can do

gs_bool = df.groupby(['B', 'C']).size() > 1

which gives

B  C
a  x     True
b  x     True
   y    False
c  z     True
dtype: bool

How do I now feed this back to df ?

You are really close - need GroupBy.transform :

gs_bool = df.groupby(['B', 'C'])['B'].transform('size') > 1
print (gs_bool)
0     True
1     True
2     True
3     True
4     True
5    False
6     True
Name: B, dtype: bool

df = df[gs_bool]
print (df)
   A  B  C
0  0  a  x
1  1  b  x
2  2  a  x
3  3  c  z
4  4  c  z
6  6  b  x

IIUC:

In [38]: df.groupby(['B','C']).filter(lambda x: len(x) > 1)
Out[38]:
   A  B  C
0  0  a  x
1  1  b  x
2  2  a  x
3  3  c  z
4  4  c  z
6  6  b  x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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