簡體   English   中英

滿足條件的數據框分組和計數值

[英]Dataframe groupby and count value satisfying conditions

這是我手頭的數據框:

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

我想計算length小於 5 的唯一id

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

如何簡單地獲得長度低於 5 的總 ID? 就像是:

df[where df.length<5]
1

只需在過濾器后使用nunique

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM