简体   繁体   中英

Python pandas dataframe group by based on a condition

My question is simple, I have a dataframe and I groupby the results based on a column and get the size like this:

df.groupby('column').size()

Now the problem is that I only want the ones where size is greater than X . I am wondering if I can do it using a lambda function or anything similar? I have already tried this:

df.groupby('column').size() > X

and it prints out some True and False values.

The grouped result is a regular DataFrame, so just filter the results as usual:

 import pandas as pd

 df = pd.DataFrame({'a': ['a', 'b', 'a', 'a', 'b', 'c', 'd']})
 after = df.groupby('a').size()
 >> after
 a
 a    3
 b    2
 c    1
 d    1
 dtype: int64

 >> after[after > 2]
 a
 a    3
 dtype: int64

试试这段代码:

df.groupby('column').filter(lambda group: group.size > 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