Skip to content

BUG: groupby().agg() loses column names for an empty dataframe with 'idxmax' as an aggregation function #42332

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
2 of 3 tasks
DFEvans opened this issue Jul 1, 2021 · 7 comments
Assignees
Labels
Apply Apply, Aggregate, Transform, Map good first issue Groupby Needs Tests Unit test(s) needed to prevent regressions
Milestone

Comments

@DFEvans
Copy link

DFEvans commented Jul 1, 2021

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • (optional) I have confirmed this bug exists on the master branch of pandas.


Note: Please read this guide detailing how to provide the necessary information for us to reproduce your bug.

Code Sample, a copy-pastable example

import pandas as pd

df = pd.DataFrame(columns=["id1", "id2", "time", "values"], dtype="int")


df_ok = df.groupby(["id1", "id2"]).sum()

print("Dataframe using .count() with groupby column names retained")
print(df_ok.index.names)


df_ok_2 = df.groupby(["id1", "id2"]).agg(**{
    "start": pd.NamedAgg(column="time", aggfunc="min"),
})

print()
print("Dataframe using aggfunc='min' with groupby columns retained")
print(df_ok_2.index.names)


df_bad = df.groupby(["id1", "id2"]).agg(**{
    "start": pd.NamedAgg(column="time", aggfunc="min"),
    "peak_time": pd.NamedAgg(column="values", aggfunc="idxmax")
})

print()
print("Dataframe using aggfunc='min' and aggfunc='idxmax' with groupby column names lost")
print(df_bad.index.names)


df_bad = df.groupby(["id1", "id2"]).agg(**{
    "peak_time": pd.NamedAgg(column="values", aggfunc="idxmax")
})

print()
print("Dataframe using only aggfunc='idxmax' with groupby columns lost entirely")
print(df_bad.index.names)

Output:

Dataframe using .count() with groupby column names retained
['id1', 'id2']

Dataframe using aggfunc='min' with groupby columns retained
['id1', 'id2']

Dataframe using aggfunc='min' and aggfunc='idxmax' with groupby column names lost
[None, None]

Dataframe using only aggfunc='idxmax' with groupby columns lost entirely
[None]

Problem description

The index returned by DataFrame.groupby().agg() is inconsistent depending on the aggregation applied to the groupby for an empty dataframe. This makes it difficult to use the output of these functions without adding subsequent if/else blocks to re-build the index names.

In the above examples, the provided DataFrame is empty. The behaviour of the returned DataFrames differs by how I handle the groupby:

  1. If I use a function like .count(), the 'groupby' columns are both retained, and their names are kept, as I expect
  2. If I use .agg() with 'min' as the function, the same good behaviour occurs
  3. If I use .agg() with two functions, one being 'min' and the other 'idxmin', two index columns are returned but their names are lost, becoming 'level_0' and 'level_1'
  4. If I use .agg() with only 'idxmin' as the function, only a single index column is returned, even though I grouped by two columns.

In Pandas 1.1.5, the third case behaved well, remembering the column names; the behaviour changed in 1.2.0.

Expected Output

The groupby columns and their names are remembered in all cases.

Output of pd.show_versions()

INSTALLED VERSIONS

commit : 7c48ff4
python : 3.8.6.final.0
python-bits : 64
OS : Linux
OS-release : 3.10.0-1160.31.1.el7.x86_64
Version : #1 SMP Tue Jun 15 10:20:52 CDT 2021
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_GB.UTF-8
LOCALE : en_GB.UTF-8

pandas : 1.2.5
numpy : 1.19.4
pytz : 2021.1
dateutil : 2.8.1
pip : 21.1.3
setuptools : 41.6.0
Cython : None
pytest : 6.2.4
hypothesis : None
sphinx : 3.5.4
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : 2.9.1 (dt dec pq3 ext lo64)
jinja2 : 3.0.1
IPython : None
pandas_datareader: None
bs4 : None
bottleneck : None
fsspec : 2021.06.0
fastparquet : None
gcsfs : None
matplotlib : 3.4.2
numexpr : None
odfpy : None
openpyxl : 3.0.7
pandas_gbq : None
pyarrow : 3.0.0
pyxlsb : None
s3fs : None
scipy : 1.7.0
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
numba : 0.53.1

@DFEvans DFEvans added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Jul 1, 2021
@mroeschke mroeschke added Apply Apply, Aggregate, Transform, Map good first issue Groupby Needs Tests Unit test(s) needed to prevent regressions and removed Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Aug 21, 2021
@calvh
Copy link
Contributor

calvh commented Aug 21, 2021

take

@PurnashisHazra
Copy link

Can I work on this?

@goyaldhara
Copy link

take

@charuu
Copy link

charuu commented Aug 26, 2021

I am new to contributing to open source projects. Can I work on this issue?

@ranit-chatterjee
Copy link

Can I contribute to your issue?
p.s.: I'm new to git, so if possible I'll be needing some guidance!

@ranit-chatterjee
Copy link

@DFEvans

I think the issue has already been solved but I think there maybe some syntax error which would I like to point out!

import numpy as np
import pandas as pd

df=pd.DataFrame({'A':np.random.poisson(5,size=10),
                'B':np.random.randn(10),
                'C':np.array(['Ally','Sally','Tally','Tapply','Riley','Wiley','Zipf','Poisson','Gamma','Beta']),
                'D':np.array([1,2,3,4,4,4,5,2,1,3])})

df.groupby(['D']).agg(['max','idxmin'])
df.groupby(['D','A']).agg(['max','idxmin'])

@DFEvans
Copy link
Author

DFEvans commented Aug 31, 2021

Looks like it is now fixed - Pandas 1.3.0 and higher retains the index for all four examples in the original issue:

Dataframe using .count() with groupby column names retained
['id1', 'id2']

Dataframe using aggfunc='min' with groupby columns retained
['id1', 'id2']

Dataframe using aggfunc='min' and aggfunc='idxmax' with groupby column names lost
['id1', 'id2']

Dataframe using only aggfunc='idxmax' with groupby columns lost entirely
['id1', 'id2']

@DFEvans DFEvans closed this as completed Aug 31, 2021
@jreback jreback added this to the 1.4 milestone Aug 31, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Apply Apply, Aggregate, Transform, Map good first issue Groupby Needs Tests Unit test(s) needed to prevent regressions
Projects
None yet
Development

Successfully merging a pull request may close this issue.

8 participants