Skip to content

BUG: Dataframe.groupby.apply misplaces Index within object #41477

Open
@tlaytongoogle

Description

@tlaytongoogle
  • 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.


Code Sample, a copy-pastable example

From https://replit.com/@tlaytongoogle/DFGroupbyBadIndex:

import pandas as pd

class Wrapper:
  def __init__(self, value):
    self.value = value

df = pd.DataFrame({'key': ['a', 'b']}, index=['foo', 'bar'])
print('df:\n' + str(df))

def f(group_df):
  print('group_df:\n' + str(group_df))  # Correct
  return Wrapper(group_df.index)

y = df.groupby('key').apply(f)

print('Value within `a`:\n' + str(y.loc['a'].value))  # Correct
print('Value within `b`:\n' + str(y.loc['b'].value))  # Ought to be `pd.Index(['foo'])``

Problem description

When DataFrame.groupby.apply is given a function that returns an object, which in turn has a field containing an Index, the resulting Series of objects is incorrect in a specific way: the objects' fields all contain the same Index, which only one of those objects ought to contain, instead of each containing the correct Index as it appeared in the return value of the function.

Expected Output

See reproduction above. Note that the Index values are all correct as printed from within the applied function, but not as later printed from the returned Series.

Output of pd.show_versions()

INSTALLED VERSIONS

commit : 2cb9652
python : 3.8.9.final.0
python-bits : 64
OS : Linux
OS-release : 5.4.0-1043-gcp
Version : #46-Ubuntu SMP Mon Apr 19 19:17:04 UTC 2021
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : en_US.UTF-8
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 1.2.4
numpy : 1.20.3
pytz : 2021.1
dateutil : 2.8.1
pip : 19.3.1
setuptools : 49.2.1
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : 1.1
pymysql : None
psycopg2 : None
jinja2 : 2.11.3
IPython : None
pandas_datareader: None
bs4 : None
bottleneck : None
fsspec : None
fastparquet : None
gcsfs : None
matplotlib : 3.4.1
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyxlsb : None
s3fs : None
scipy : 1.4.1
sqlalchemy : 1.4.13
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
numba : 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