Skip to content

Can't use a lambda function in named aggregation #28467

@rafaelcf0

Description

@rafaelcf0

Code Sample, a copy-pastable example if possible

animals = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
                            'height': [9.1, 6.0, 9.5, 34.0],
                            'weight': [7.9, 7.5, 9.9, 198.0]})

# Yields an error
animals.groupby('kind').agg(mean_height=('height', 'mean'),
                            perc90=('height', lambda s: np.percentile(s, q=0.90)))

def myfunc(s): return np.percentile(s, q=0.90)

# Works just fine
animals.groupby('kind').agg(mean_height=('height', 'mean'),
                            perc90=('height', myfunc))

Problem description

When I groupby+agg with a named function, the named aggregation works perfectly. However, when done with a lambda function instead, the following error is raised:

KeyError: "[('height', '<lambda>')] not in index"

Notice that his is not error 7186 because there are no more than one lambda here.

I've noticed that this error only happens when I mix lambda functions along with str-mapped functions, i.e. just

animals.groupby('kind').agg(perc90=('height', lambda s: np.percentile(s, q=0.90)))

works just fine.

Expected Output

      mean_height  perc95
kind
cat           9.3  9.1038
dog          20.0  6.2660

Output of pd.show_versions()

INSTALLED VERSIONS

commit : None
python : 3.7.4.final.0
python-bits : 64
OS : Linux
OS-release : 4.15.0-1036-gcp
machine : x86_64
processor :
byteorder : little
LC_ALL : None
LANG : C.UTF-8
LOCALE : en_US.UTF-8

pandas : 0.25.1
numpy : 1.17.2
pytz : 2019.2
dateutil : 2.8.0
pip : 19.0.3
setuptools : 40.8.0
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : None
IPython : None
pandas_datareader: None
bs4 : None
bottleneck : None
fastparquet : None
gcsfs : None
lxml.etree : None
matplotlib : 3.1.1
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pytables : None
s3fs : None
scipy : 1.3.1
sqlalchemy : None
tables : None
xarray : None
xlrd : None
xlwt : None
xlsxwriter : None
[paste the output of pd.show_versions() here below this line]

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions