简体   繁体   中英

SQL to Pandas? Group by and count

Trying to find the pandas equivalent for the following SQL:

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.

It's size :

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

Or named agg :

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

pandas ,内置函数value_counts

df['KnownSince'].value_counts()

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