分组依据,在 pandas 中

use*_*407 5 python group-by pandas

select df.id, count(distinct airports) as num
from df
group by df.id
having count(distinct airports) > 3
Run Code Online (Sandbox Code Playgroud)

我正在尝试在 Python pandas 中执行与上述相同的操作。我尝试了filternunique、 、的不同组合agg,但没有任何效果。有什么建议吗?

例如:df

df   
id     airport
1      lax
1      ohare
2      phl
3      lax
2      mdw
2      lax
2      sfw
2      tpe
Run Code Online (Sandbox Code Playgroud)

所以我希望结果是:

id     num
2      5
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 3

您可以SeriesGroupBy.nuniqueboolean indexing或 一起使用query

s = df.groupby('id')['airport'].nunique()
print (s)
id
1    2
2    5
3    1
Name: airport, dtype: int64

df1 = s[s > 3].reset_index()
print (df1)
   id  airport
0   2        5
Run Code Online (Sandbox Code Playgroud)

或者:

df1 = df.groupby('id')['airport'].nunique().reset_index().query('airport > 3')
print (df1)
   id  airport
1   2        5
Run Code Online (Sandbox Code Playgroud)