Python para Data Science e Analytics
Python para Data Science e Analytics › Guides › pandas groupby with multiple functions (and the result that

pandas groupby with multiple functions (and the result that misleads you)

In pandas, you apply multiple functions to a groupby with `.agg()`: pass a list of functions, a dictionary per column, or a named aggregation. The common trap is that a list of functions returns a MultiIndex in the columns, and that shape is easy to read incorrectly. The steps below show the reliable patterns and the cases where the number is not what it looks like.

Topics: pandas, groupby

How do you use groupby in pandas with multiple functions?

`groupby` follows split-apply-combine. You choose the key columns, pandas creates one group per combination of key values, and the function you pass runs inside each group. The results are then combined into a new DataFrame.

The direct pattern is a dictionary: `df.groupby('category').agg({'value': ['sum', 'mean'], 'qty': 'count'})`. Each value column receives the functions you list, and the count column receives `count`.

With two keys, `df.groupby(['category', 'month']).agg(...)`, every extra key becomes another level in the row index. That is useful for reports, but it needs attention when you export or plot the result.

Why does agg with a list of functions create two-level columns?

When you pass a list of functions, pandas creates one column for each column-function pair. The columns become a MultiIndex: the first level is the original column name, and the second level is the function name. The row index still holds the group key.

That is not an error; it is the output shape. The problem appears later. When you export to CSV or plot the result, the two-level header can become two title rows and make the table hard to read.

`as_index=False` controls the row index: the key stops being an index and becomes a column. It does not flatten the columns created by a list of functions. To avoid the issue at the source, use named aggregation: `df.groupby('category').agg(total=('value', 'sum'), ticket=('value', 'mean'))`. Each result already has an explicit name and simple columns.

If the MultiIndex result already exists, `df.columns = ['_'.join(map(str, c)) for c in df.columns]` flattens the names. It works, but it is a patch: the final name depends on column order and breaks when the grouping changes.

Why doesn't the average of group averages match the overall average?

This is the most common trap. If you calculate the mean inside each group and then average those means, the result matches the overall mean only when every group has the same number of rows. With unequal group sizes, the average of averages gives equal weight to groups that do not have equal weight in the data.

The right path depends on the question. For the overall mean, calculate it directly on the column. For the mean per group, use `groupby`. To keep the original row granularity, use `transform('mean')` instead of `agg`.

Two other details change the count. `count()` ignores missing values, while `size()` counts group rows, including rows with nulls. `mean()` also ignores nulls by default, so the mean of a group with many nulls is calculated over fewer rows than you may expect.

In categorical columns, categories with no observations can appear as empty groups. `observed=True` limits the result to categories that actually exist in the data. To keep rows with a null key, evaluate `dropna=False` and read the result carefully.

What else makes a groupby result look correct when it isn't?

Dtypes are a quiet source of wrong output. A numeric column stored as text may sum by concatenation or fail on `mean`. A date stored as text will not group by month until you convert it to a datetime type.

Missing keys are another quiet source. By default, `groupby` drops rows whose key is null. That can remove records from the totals without any warning. `dropna=False` keeps those rows as a group, but the group label may be null, so check how the output is used.

Mixed aggregation also changes shape. `agg` returns one row per group, while `transform` returns the same number of rows as the input. If you assign a transformed column back to the original DataFrame, confirm that the index alignment is what you expect.

For categorical keys, `observed=True` can remove empty category groups. That is often the correct behavior, but it changes the number of rows in the output. Compare the result with the categories in the source before you conclude that data is missing.

How do you flatten, rename, and export groupby output safely?

Use named aggregation when you control the query. It gives you simple column names, avoids a MultiIndex in the columns, and makes the export readable without extra cleanup.

When the result already has a MultiIndex, `reset_index()` moves the group key back into a column. If you must flatten column names, join the levels explicitly and inspect the output instead of assuming the order.

For CSV export, set `index=False` after `reset_index()` unless the index is meaningful in the file. For charts, simple column names are easier to map to axes and labels.

How can you practice groupby and catch these mistakes?

Reading the docs is not enough for these traps. You need guided exercises with real tables, where you compare `count()` and `size()`, check group sizes before averaging means, and export a result without a MultiIndex surprise.

The Python for Data Science and Analytics course covers pandas, data cleaning, outlier detection, and a final end-to-end project with exploratory analysis and machine learning. It starts with IDE and Jupyter Notebook setup and does not require prior programming. Lessons are recorded, watched at your own pace, with lifetime access, exercises, a certificate, and a private community.

Course details are at python.paanalytics.net. Enrollment runs through Hotmart checkout, with card or boleto; the course is R$ 470, or 12 payments of R$ 20.37 on card.

FAQ

See the Python for Data Science and Analytics course

Secure payment via Hotmart, up to 12 installments.

Enroll now Product site

Frequently asked questions

Can agg apply different functions to different columns?

Yes. Pass a dictionary where each column maps to one function or a list of functions, such as `df.groupby('category').agg({'value': ['sum', 'mean'], 'qty': 'count'})`. A list creates MultiIndex columns; a single function per column gives a simpler shape.

What is the difference between agg and transform in pandas groupby?

`agg` returns one row per group. `transform` returns the same number of rows as the original DataFrame, with the group result repeated on each row. Use `agg` for summaries and `transform` when you need a group value as a new column.

How do I keep the group key as a column instead of an index?

Use `as_index=False` in `groupby`, or call `reset_index()` on the result. `as_index=False` changes the row index only; it does not flatten MultiIndex columns created by a list of functions.

Why does count return a different number from size?

`count()` counts non-null values for each column, so it ignores nulls. `size()` counts the rows in each group, including rows with nulls. Compare both when you need to know how many records a group really has.

How do I include rows with a missing group key?

By default, `groupby` drops rows whose key is null. Use `dropna=False` to keep them as a group, then check how the null label appears in the output and whether it belongs in your totals.

Ler em português →