简体   繁体   中英

Dataframe groupby and count value satisfying conditions

This is the dataframe I have at hand:

df = pd.DataFrame({
    'id': [1,1,1,2,2,3,3],
    'length': [20, 20, 20, 4, 4, 15,15],
    'speed': [17.2,16.5,18, 2.3,2.1,10,9.8]
})

df
    id  length  speed
0   1    20     17.2
1   1    20     16.5
2   1    20     18.0
3   2     4     2.3
4   2     4     2.1
5   3    15     10.0
6   3    15     9.8

I want to count unique id whose length is less than 5.

df[df['length']<5].groupby('id')['length'].value_counts()
id  length
2   4         2
Name: length, dtype: int64

How do I simply get total id with length below 5? something like:

df[where df.length<5]
1

Just use nunique after the filter:

df[df.length < 5].id.nunique()
# 1

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