Skip to content

BUG: GROUPING UNPOPULATED DATAFRAME raises exception - index name clashes with duplicate column name #44350

Closed
@sjvdm

Description

@sjvdm

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

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

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

Reproducible Example

## GROUPING POPULATED DATAFRAME WORKS - index name does not clash with column name
df = pd.DataFrame(data={'f1':[1,2],'f2':[3,4],'f3':[5,6]})
df.groupby('f1').apply(lambda x: x.loc[:,'f2'].nunique()).reset_index()

#=======================================================================
## GROUPING UNPOPULATED DATAFRAME raises exception - index name clashes with duplicate column name
df = pd.DataFrame(columns=['f1','f2','f3'])
df = df.groupby('f1').apply(lambda x: x.loc[:,'f2'].nunique()).reset_index()

'''
ValueError: cannot insert f1, already exists
'''

Issue Description

There is inconsistent behaviour when grouping a populated dataframe and an empty dataframe in terms of index naming. When the index is reset, an empty dataframe will raise an exception on duplicate key.

Expected Behavior

Even when the dataframe is empty, it should not have the groupby key as a column (as with a populated dataframe)

Installed Versions

INSTALLED VERSIONS

commit : 945c9ed
python : 3.8.3.final.0
python-bits : 64
OS : Linux
OS-release : 4.18.0-240.22.1.el8_3.x86_64
Version : #1 SMP Thu Apr 8 19:01:30 UTC 2021
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 1.3.4
numpy : 1.20.3
pytz : 2021.1
dateutil : 2.8.1
pip : 21.3.1
setuptools : 46.4.0
Cython : 0.29.23
pytest : 6.2.4
hypothesis : None
sphinx : None
blosc : None
feather : None

Metadata

Metadata

Assignees

No one assigned

    Labels

    ApplyApply, Aggregate, Transform, MapBugGroupby

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions