简体   繁体   English

SQL 到 Pandas? 分组和计数

[英]SQL to Pandas? Group by and count

Trying to find the pandas equivalent for the following SQL:尝试为以下 SQL 找到等效的 Pandas:

SELECT KnownSince, COUNT(1)
FROM mytable
GROUP BY KnownSince

I have already tested:我已经测试过:

aux.groupby(['KnownSince'])['KnownSince'].agg(['count']),  
aux.groupby(['KnownSince']).agg(['count']),  
aux['KnownSince'].groupby(['KnownSince']).agg(['count']),  
aux['KnownSince'].groupby().agg(['count'])

But didn't achieve expexted result.但没有达到预期的效果。

PS: KnownSince is a number in the format YYYYMM and not a datetime object. PS: KnownSince是格式为 YYYYMM 的数字,而不是日期时间对象。

It's size :它的size

df.groupby('KnownSince', as_index=False).size()

Or named agg :或命名为agg

df.groupby('KnownSince').agg(count=('KnownSince','count')).reset_index()

pandas ,内置函数value_counts

df['KnownSince'].value_counts()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM