Skip to content

BUG: groupby __iter__ on pandas 1.1.x not propagating _metadata on DataFrame subclasses #37343

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
3 tasks done
ryandvmartin opened this issue Oct 22, 2020 · 6 comments · Fixed by #37461
Closed
3 tasks done
Labels
Groupby metadata _metadata, .attrs Regression Functionality that used to work in a prior pandas version
Milestone

Comments

@ryandvmartin
Copy link

ryandvmartin commented Oct 22, 2020

  • 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

In [1]: import pandas as pd
   ...:
   ...: class SubclassedDataFrame2(pd.DataFrame):
   ...:
   ...:     # temporary properties
   ...:     _internal_names = pd.DataFrame._internal_names + ['internal_cache']
   ...:     _internal_names_set = set(_internal_names)
   ...:
   ...:     # normal properties
   ...:     _metadata = ['added_property']
   ...:
   ...:     @property
   ...:     def _constructor(self):
   ...:         return SubclassedDataFrame2
   ...:

In [2]: df = SubclassedDataFrame2({'A': [1, 2, 3], 'B': [1, 1, 2], 'C': [7, 8, 9]})
   ...: df.added_property = "hello"
   ...: for i, d in df.groupby("B"):
   ...:     assert d.added_property == "hello"
   ...:
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-2-bf64fc505324> in <module>
      2 df.added_property = "hello"
      3 for i, d in df.groupby("B"):
----> 4     assert d.added_property == "hello"
      5

~\RMS-Python\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
   5133             or name in self._accessors
   5134         ):
-> 5135             return object.__getattribute__(self, name)
   5136         else:
   5137             if self._info_axis._can_hold_identifiers_and_holds_name(name):

AttributeError: 'SubclassedDataFrame2' object has no attribute 'added_property'

Problem description

Under pandas 1.0.x the above is working, on 1.1.x, the _metadata is not propagated to the split frames. I think this is a known issue with groupby and __finalize__, but this specific behavior with __iter__ is a regression from 1.0.x behavior on DataFrame subclasses.

Expected Output

Assert statements above are passing, with metadata propagated to the split dataframe

Output of pd.show_versions()

INSTALLED VERSIONS

commit : db08276
python : 3.7.7.final.0
python-bits : 64
OS : Windows
OS-release : 10
Version : 10.0.19041
machine : AMD64
processor : AMD64 Family 23 Model 113 Stepping 0, AuthenticAMD
byteorder : little
LC_ALL : None
LANG : None
LOCALE : None.None

pandas : 1.1.3
numpy : 1.18.1
pytz : 2020.1
dateutil : 2.8.1
pip : 20.0.2
setuptools : 46.1.3.post20200330
Cython : 0.29.17
pytest : 5.4.1
hypothesis : 5.36.1
sphinx : 2.4.4
blosc : None
feather : None
xlsxwriter : 1.2.8
lxml.etree : 4.5.0
html5lib : 1.0.1
pymysql : None
psycopg2 : None
jinja2 : 2.11.2
IPython : 7.13.0
pandas_datareader: None
bs4 : 4.9.0
bottleneck : 1.3.2
fsspec : 0.8.0
fastparquet : None
gcsfs : None
matplotlib : 3.1.3
numexpr : 2.7.1
odfpy : None
openpyxl : 3.0.3
pandas_gbq : None
pyarrow : None
pytables : None
pyxlsb : None
s3fs : None
scipy : 1.4.1
sqlalchemy : 1.3.16
tables : 3.6.1
tabulate : None
xarray : None
xlrd : 1.2.0
xlwt : 1.3.0
numba : 0.49.0

@ryandvmartin ryandvmartin added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Oct 22, 2020
@ryandvmartin
Copy link
Author

related comment and existing possible fix: #28283 (comment)

@jorisvandenbossche jorisvandenbossche added Groupby metadata _metadata, .attrs Regression Functionality that used to work in a prior pandas version and removed Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Oct 27, 2020
@jorisvandenbossche jorisvandenbossche added this to the 1.1.4 milestone Oct 27, 2020
@jorisvandenbossche
Copy link
Member

Thanks for the report!
This was not yet fixed by #35688 ?

@ryandvmartin
Copy link
Author

I don't think it was fixed there.

I think #37461 is on the right track - I have tracked our specific issue to _chop() in the context of the groupby iterable on 1.0.x in pandas/core/groupby/ops.py:973

in FrameSplitter._chop:

modifying:

    def _chop(self, sdata: DataFrame, slice_obj: slice) -> DataFrame:
        # Fastpath equivalent to:
        # if self.axis == 0:
        #     return sdata.iloc[slice_obj]
        # else:
        #     return sdata.iloc[:, slice_obj]
        mgr = sdata._mgr.get_slice(slice_obj, axis=1 - self.axis)
        return type(sdata)(mgr)

to

    def _chop(self, sdata: DataFrame, slice_obj: slice) -> DataFrame:
        # Fastpath equivalent to:
        # if self.axis == 0:
        #     return sdata.iloc[slice_obj]
        # else:
        #     return sdata.iloc[:, slice_obj]
        mgr = sdata._mgr.get_slice(slice_obj, axis=1 - self.axis)
        return type(sdata)(mgr).__finalize__(sdata)

Propogates the metdata, but as I understand it there are places to and to not use __finalize__ (#28283)

@simonjayhawkins simonjayhawkins modified the milestones: 1.1.4, 1.1.5 Oct 29, 2020
@simonjayhawkins
Copy link
Member

I think #37461 is on the right track

the code sample passes with that PR in it's current state. I'll comment there about adding a test for this issue.

However, that PR still needs review and 1.1.4 is scheduled for tomorrow, so moving off 1.1.4 milestone for now.

simonjayhawkins added a commit to simonjayhawkins/pandas that referenced this issue Oct 29, 2020
@simonjayhawkins
Copy link
Member

Under pandas 1.0.x the above is working, on 1.1.x, the _metadata is not propagated to the split frames. I think this is a known issue with groupby and __finalize__, but this specific behavior with __iter__ is a regression from 1.0.x behavior on DataFrame subclasses.

first bad commit: [6f065b6] PERF: faster indexing for non-fastpath groupby ops (#34214) cc @jbrockmendel

@Japanuspus
Copy link
Contributor

I think #37461 is on the right track - I have tracked our specific issue to _chop() in the context of the groupby iterable on 1.0.x in pandas/core/groupby/ops.py:973

I hope so -- my own code broke on the 1.1 update as well :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Groupby metadata _metadata, .attrs Regression Functionality that used to work in a prior pandas version
Projects
None yet
Development

Successfully merging a pull request may close this issue.

5 participants