Skip to main content
 首页 » 编程设计

python之Pandas groupby 和 agg 按条件

2025年05月04日8Renyi-Fan

df.groupby(['Month']).agg({'Status' : ['count']}) 

上面的行按 Month 对 dataframe 进行分组,并计算每个月的 Status 数量。有没有一种方法可以只在 Status=X 处获得计数?类似于下面的错误代码:

df.groupby(['Month']).agg({'Status' == 'X' : ['count']}) 

基本上,我想计算每个月有多少 Status 是 X。

请您参考如下方法:

让我们做点不一样的

pd.crosstab(df.Month,df.Status)['X']