Skip to content

Fix GH-29442 DataFrame.groupby doesn't preserve _metadata #35688

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

Merged
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
7cc4d53
Fix GH-29442 DataFrame.groupby doesn't preserve _metadata
Japanuspus Aug 12, 2020
0ab766d
Fix most PEP8 issues
Japanuspus Aug 12, 2020
d7b42e3
Fix remaining PEP8 issues
Japanuspus Aug 13, 2020
fbc602c
Apply "black" styling and fix typo
Japanuspus Aug 13, 2020
e9c64ac
Fix import sorting issues reported by `isort`
Japanuspus Aug 13, 2020
ec7fd00
Make testcase more concise
Japanuspus Aug 14, 2020
1405667
Include test from original issue
Japanuspus Aug 27, 2020
8d3d896
Fix metadata handling for `.groupby(...).sum()`
Japanuspus Aug 27, 2020
39e9f33
Apply black format
Japanuspus Aug 27, 2020
7075ef2
Remove xfail decorator for `sum` aggregation test
Japanuspus Sep 23, 2020
05a3365
Merge branch 'master' into BUG_GH29442_frame_groupby_metadata
Japanuspus Oct 1, 2020
4720c97
Move `__finalize__` outsize context handler
Japanuspus Oct 2, 2020
6b290e8
Revert __finalize__ call in DataSplitter
Japanuspus Oct 2, 2020
a2bdc3d
Add performance test counting __finalize__ calls
Japanuspus Oct 2, 2020
2af8447
Add whatsnew entry
Japanuspus Oct 2, 2020
ec3eeb1
Move __finalize__ inside context manager
Japanuspus Oct 2, 2020
5487563
Fix typo in whatsnew entry
Japanuspus Oct 2, 2020
8bfd08d
Revert 1.1.3 whatsnew entry
Japanuspus Oct 6, 2020
7d9320a
Merge branch 'master' into BUG_GH29442_frame_groupby_metadata
Japanuspus Oct 6, 2020
7878041
Add 1.1.4 whatsnew entry
Japanuspus Oct 6, 2020
5548699
Revert all changes not strictly related to issue
Japanuspus Oct 8, 2020
18e8ff5
Use descriptive names for unit tests
Japanuspus Oct 8, 2020
57694ae
Remove extraneous imports
Japanuspus Oct 8, 2020
d3088a3
Merge master into BUG_GH29442_frame_groupby_metadata
Japanuspus Oct 8, 2020
d86ae78
Delete tests for custom metadata
Japanuspus Oct 9, 2020
6227894
Remove reference to internal class from whatsnew
Japanuspus Oct 9, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions pandas/core/groupby/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -955,7 +955,9 @@ class SeriesSplitter(DataSplitter):
def _chop(self, sdata: Series, slice_obj: slice) -> Series:
# fastpath equivalent to `sdata.iloc[slice_obj]`
mgr = sdata._mgr.get_slice(slice_obj)
return type(sdata)(mgr, name=sdata.name, fastpath=True)
return sdata._constructor(mgr, name=sdata.name, fastpath=True).__finalize__(
sdata, method="groupby"
)


class FrameSplitter(DataSplitter):
Expand All @@ -971,7 +973,7 @@ def _chop(self, sdata: DataFrame, slice_obj: slice) -> DataFrame:
# else:
# return sdata.iloc[:, slice_obj]
mgr = sdata._mgr.get_slice(slice_obj, axis=1 - self.axis)
return type(sdata)(mgr)
return sdata._constructor(mgr).__finalize__(sdata, method="groupby")


def get_splitter(
Expand Down
89 changes: 89 additions & 0 deletions pandas/tests/groupby/test_custom_metadata.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
"""
Test metadata propagation in groupby

The PandasTable class below is implemented according to the [guidelines],
and as such would expect `__finalize__` to always be called so that the
`_pandastable_metadata` is always populated.

[guidelines]: https://pandas.pydata.org/pandas-docs/stable/development/extending.html#override-constructor-properties # noqa
"""

from typing import List
from warnings import warn

import pytest

import pandas as pd

_TABLE_METADATA_FIELD_NAME = "_pandastable_metadata"


def _combine_metadata(data: List[str]) -> str:
"""
A mock implementation for testing
"""
return "+".join(data)


class PandasTable(pd.DataFrame):
"""
A pandas dataframe subclass with associated table metadata.
"""

_metadata = [_TABLE_METADATA_FIELD_NAME] # Register metadata fieldnames here

@property
def _constructor(self):
return PandasTable

def __finalize__(self, other, method=None, **kwargs):
"""
This method will be called after constructor to populate metadata

The "method" argument is subject to change and must be handled robustly.
"""
src = [other] # more logic here in actual implementation
metadata = _combine_metadata(
[d.get_metadata() for d in src if isinstance(d, PandasTable)]
)

if not metadata:
warn(
'__finalize__ unable to combine metadata for method "{method}", '
"falling back to DataFrame"
)
return pd.DataFrame(self)
object.__setattr__(self, _TABLE_METADATA_FIELD_NAME, metadata)
return self

def get_metadata(self):
metadata = getattr(self, _TABLE_METADATA_FIELD_NAME, None)
if metadata is None:
warn("PandasTable object not correctly initialized: no metadata")
return metadata

@staticmethod
def from_table_data(df: pd.DataFrame, metadata) -> "PandasTable":
df = PandasTable(df)
object.__setattr__(df, _TABLE_METADATA_FIELD_NAME, metadata)
return df


@pytest.fixture
def dft():
df = pd.DataFrame([[11, 12, 0], [21, 22, 0], [31, 32, 1]], columns={"a", "b", "g"})
return PandasTable.from_table_data(df, "My metadata")


def test_initial_metadata(dft):
assert dft.get_metadata() == "My metadata"


def test_basic_propagation(dft):
gg = dft.loc[dft.g == 0, :]
assert gg.get_metadata() == "My metadata"


def test_groupby(dft):
gg = [ab for g, ab in dft.groupby("g")]
assert gg[0].get_metadata() is not None