pandas.core.groupby.apply result_type parameter equivalent?

24 Views Asked by At

Is there an equivalent for the result_type parameter in pandas.DataFrame.apply that helps pandas not interpret the result "smartly", so that you can return lists and dicts from apply and still have it reduce each group to the result of the function applied, rather than "smartly" expand dicts returned by the apply function to a new index level?

Looked in the documentation, seems like result_type is not documented for groupby.apply. I also tried just putting it in, didn't work.

1

There are 1 best solutions below

0
AndJ On

As an example:

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
    'B': ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
    'C': np.random.randn(8),
    'D': np.random.randn(8)
})

def my_func(x):
    d = {'mean_C': x['C'].mean(), 'mean_D': x['D'].mean()}
    return pd.Series(d, index=['mean_C', 'mean_D'])

result = df.groupby('A').apply(my_func)

print(result)

Reading through the docs of pandas.DataFrame.groupby.apply at the following link there isn't a result_type parameter.

This means that there is no direct way to control how the results are interpreted when returning a dictionary or list.

However, there is a way around this problem. You can convert the result of your function to a series before returning it. This way, pandas will not try to expand the result into a new index level.