如何在Python3的Pandas中实现分组求和与计数?
groupby with sum() and count() in Pandas Great question! When you need to run multiple aggregations (like summing values and counting entries) after grouping your Pandas DataFrame, the .agg() (aggregate) method is your best bet—it lets you specify exactly which functions to apply to which columns. Here's how to do it with your emendas_exec_geral dataset:
Example 1: Group by Autor to get total approved value and emenda count
Let's say you want to see each author's total approved value and how many emendas they've submitted. Here's the code:
import pandas as pd # Load your data (as you already did) emendas_exec_geral = pd.read_csv("emendas_geral_autores.csv", sep=',', encoding='utf-8') # Group by 'Autor' and run both sum and count aggregations aggregated_data = emendas_exec_geral.groupby('Autor').agg( total_valor_aprovado=('Valor_aprovado', 'sum'), # Sum all approved values per author numero_emendas=('Emenda', 'count') # Count how many emendas per author ).reset_index() # Convert 'Autor' from index back to a regular column # Check the result print(aggregated_data.head())
Breaking down the code:
groupby('Autor'): Groups the DataFrame by unique values in theAutorcolumn..agg(...): This is where you define your aggregations. We use named arguments to create clear, descriptive column names for the results. Each argument takes a tuple:(source_column, aggregation_function).reset_index(): By default, the grouping column (Autor) becomes the index of the result. Using this method makes it a regular column again, which is usually easier to work with.
Example 2: Group by multiple columns
If you want to group by more than one column (like Autor and UO_Ajustada), just pass a list to groupby:
# Group by two columns and aggregate aggregated_multi = emendas_exec_geral.groupby(['Autor', 'UO_Ajustada']).agg( total_valor=('Valor_aprovado', 'sum'), total_registros=('Emenda', 'count') ).reset_index() print(aggregated_multi.head())
Key note: count() vs size()
count()counts non-null entries in the specified column. Since all your columns have no nulls (per yourinfo()output), this will equal the number of rows in the group.size()returns the total number of rows in each group, regardless of null values. If you want to get the group size directly, use:
aggregated_size = emendas_exec_geral.groupby('Autor').agg( total_valor=('Valor_aprovado', 'sum'), tamanho_grupo=('Autor', 'size') # Gets total rows per author group ).reset_index()
Alternative: Dictionary syntax
If you prefer (or are using an older Pandas version), you can use a dictionary to define aggregations:
agg_dict = { 'Valor_aprovado': 'sum', 'Emenda': 'count' } aggregated_dict = emendas_exec_geral.groupby('Autor').agg(agg_dict).reset_index() # Rename columns for clarity (default names are (column, function)) aggregated_dict.columns = ['Autor', 'total_valor_aprovado', 'numero_emendas']
You can adjust the grouping columns (e.g., Funcional, UO_Ajustada) and aggregation functions (like mean(), max()) to fit whatever analysis you need!
内容的提问来源于stack exchange,提问作者Reinaldo Chaves

