Python 如何在熊猫中按2列分组和执行计数

Python 如何在熊猫中按2列分组和执行计数,python,pandas,Python,Pandas,如何在pandas中执行这样的查询 Select col1, col2, count(col3) as total from table GROUP by col1,col2 您需要以下方法: 这将为您提供所有其他列的计数。如果要为每列指定不同的聚合函数,可以使用.agg: df2 = df.groupby(['col1', 'col2'], as_index = False).agg({'col3': 'count', 'col4': 'sum'}) 请参阅文档。df=df.groupby

如何在pandas中执行这样的查询

Select col1, col2, count(col3) as total from table
GROUP by col1,col2
您需要以下方法:

这将为您提供所有其他列的计数。如果要为每列指定不同的聚合函数,可以使用
.agg

df2 = df.groupby(['col1', 'col2'], as_index = False).agg({'col3': 'count', 'col4': 'sum'})

请参阅文档。
df=df.groupby(['col1','col2'])['col3'].count().reset_index().rename(columns={'col3':'total'})
仍然得到与我的查询结果不同的结果
df2 = df.groupby(['col1', 'col2'], as_index = False).agg({'col3': 'count', 'col4': 'sum'})