Skip to content

Wrong index type from groupby on an empty dataframe using user-defined agg func #14538

Closed
@simonbrownsb

Description

@simonbrownsb

A small, complete example of the issue

import pandas as pd

df = pd.DataFrame(columns=['a', 'b'])
df2 = df.groupby('a').agg({
    'a': {'max_a': lambda x: x.max()},
    'b': {'count_b': 'count'}
})
print(df2.index)

Expected Output

Index([], dtype='object', name='a') 

(This is the sort of index you would get if it wasn't an empty dataframe, or if the aggregation function was a cythoned builtin string like 'max').

Actual Output

RangeIndex(start=0, stop=0, step=1)

Nondeterministic in Python3 (sometimes the expected result, sometimes not, with the same code, on different runs).

Deterministically wrong in Python2 (provided the outer agg dictionary is ordered so that the user-defined function agg appears first in the list of keys).

Output of pd.show_versions()

## INSTALLED VERSIONS

commit: None
python: 3.4.3.final.0
python-bits: 64
OS: Darwin
OS-release: 15.5.0
machine: x86_64
processor: i386
byteorder: little
LC_ALL: None
LANG: en_GB.UTF-8

pandas: 0.18.1
nose: None
pip: 6.0.8
setuptools: 12.2
Cython: 0.24.1
numpy: 1.11.1
scipy: None
statsmodels: None
xarray: None
IPython: None
sphinx: None
patsy: None
dateutil: 2.5.3
pytz: 2016.6.1
blosc: None
bottleneck: None
tables: None
numexpr: None
matplotlib: 1.5.3
openpyxl: None
xlrd: None
xlwt: None
xlsxwriter: None
lxml: None
bs4: None
html5lib: None
httplib2: None
apiclient: None
sqlalchemy: None
pymysql: None
psycopg2: None
jinja2: 2.7.3
boto: None
pandas_datareader: None

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions