-
-
Notifications
You must be signed in to change notification settings - Fork 18.4k
REF/ENH: Refactor NDFrame finalization #28334
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
Closed
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
8370e39
REF/ENH: Refactor NDFrame finalization
TomAugspurger d7bb99c
refactor
TomAugspurger 60bc89c
Merge remote-tracking branch 'upstream/master' into metadata-dispatch
TomAugspurger b05782c
move to meta
TomAugspurger 53576eb
mypy
TomAugspurger 3009732
fixed subclass
TomAugspurger d68e5bb
Merge remote-tracking branch 'upstream/master' into metadata-dispatch
TomAugspurger 710d73a
define API
TomAugspurger ecf3989
simplify
TomAugspurger File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,130 @@ | ||
""" | ||
Metadata propagation through pandas operations. | ||
|
||
This module contains the infrastructure for propagating ``NDFrame._metadata`` | ||
through operations. We perform an operation (say :meth:`pandas.Series.copy`) that | ||
returns an ``NDFrame`` and would like to propagate the metadata (say ``Series.name``) | ||
from ``self`` to the new ``NDFrame``. | ||
""" | ||
from typing import TYPE_CHECKING, Any, Dict | ||
|
||
from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries | ||
|
||
if TYPE_CHECKING: | ||
from pandas._typing import FrameOrSeries | ||
|
||
|
||
class PandasMetadataType(type): | ||
""" | ||
Metaclass controlling creation of metadata finalizers. | ||
|
||
This ensures we have one finalizer instance per name, and | ||
provides a place to look up finalizer per name. | ||
""" | ||
|
||
# TODO(Py35): Replace metaclass with __subclass_init__ | ||
|
||
_instances = {} # type: Dict[str, "PandasMetadata"] | ||
|
||
def __init__(self, *args, **kwargs): | ||
super().__init__(*args, **kwargs) | ||
|
||
def __call__(self, name, *args: Any, **kwds: Any) -> Any: # type: ignore | ||
if name in self._instances: | ||
return self._instances[name] | ||
else: | ||
new = super().__call__(name, *args, **kwds) | ||
self._instances[name] = new | ||
return new | ||
|
||
|
||
class PandasMetadata(metaclass=PandasMetadataType): | ||
""" | ||
Dispatch metadata finalization for pandas metadata. | ||
|
||
Parameters | ||
---------- | ||
name : str | ||
The name of the attribute being finalized. | ||
|
||
Examples | ||
-------- | ||
If you want the default resolution (copy from a source NDFrame | ||
to a new NDFrame), you can just create an instance | ||
|
||
>>> mymeta = PandasMetadata("mymeta") | ||
|
||
If you need custom metadata resolution, you'll need to subclass. | ||
|
||
>>> class IncrementMetadata: | ||
... def default(self, new, other): | ||
... setattr(new, self.attr, getattr(other, self.name, -1) + 1) | ||
|
||
>>> increment_metadata = IncrementMetadata("attr") | ||
""" | ||
|
||
def __init__(self, name: str): | ||
self.name = name | ||
|
||
def __repr__(self): | ||
return "PandasMetadata(name='{}')".format(self.name) | ||
|
||
def finalize(self, new: "FrameOrSeries", other: Any, method): | ||
""" | ||
Run the finalization for `method`. | ||
|
||
Parameters | ||
---------- | ||
new : DataFrame or Series | ||
other : Any | ||
One of the following types | ||
|
||
* DataFrame | ||
* Series | ||
* Concatenator | ||
* MergeOperation | ||
|
||
method : str | ||
The source method. | ||
|
||
Returns | ||
------- | ||
None | ||
Expected to operate inplace. | ||
|
||
Notes | ||
----- | ||
The default implementation simply calls ``.default``, ignoring `method`. | ||
""" | ||
self.default(new, other) | ||
|
||
def default(self, new: "FrameOrSeries", other: Any): | ||
""" | ||
The default finalizer when this method, attribute hasn't been overridden. | ||
|
||
This copies the ``_metadata`` attribute from ``other`` to ``self``, modifying | ||
``self`` inplace. | ||
|
||
Parameters | ||
---------- | ||
new : NDFrame | ||
The newly created NDFrame being finalized. | ||
other : Any | ||
The source object attributes will be extracted from. | ||
""" | ||
# TODO: check perf on this isinstance. | ||
if isinstance(other, (ABCSeries, ABCDataFrame)): | ||
object.__setattr__(new, self.name, getattr(other, self.name, None)) | ||
|
||
|
||
class NameMetadata(PandasMetadata): | ||
"""Finalization for Series.name""" | ||
|
||
|
||
# TODO: having to create this here feels weird. | ||
name_metadata = NameMetadata("name") | ||
|
||
# For backwards compat. Do we care about this? | ||
# We can pretty easily deprecate, require subclasses to make their | ||
# own instance. | ||
default_finalizer = PandasMetadata("pandas") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
import pytest | ||
|
||
import pandas as pd | ||
from pandas.core.meta import PandasMetadata | ||
|
||
|
||
class MyMeta(PandasMetadata): | ||
def finalize(self, new, other, method): | ||
if method == "concat": | ||
self.finalize_concat(new, other) | ||
elif method == "copy": | ||
self.finalize_copy(new, other) | ||
else: | ||
super().finalize(new, other, method) | ||
|
||
def default(self, new, other): | ||
new.attr = other.attr + 1 | ||
|
||
def finalize_concat(self, new, other): | ||
assert isinstance(other, pd.core.reshape.concat._Concatenator) | ||
new.attr = sum(x.attr for x in other.objs) | ||
|
||
|
||
mymeta = MyMeta("attr") | ||
|
||
|
||
@pytest.fixture | ||
def custom_meta(monkeypatch): | ||
original_metadata = [] | ||
|
||
for cls in [pd.Series, pd.DataFrame]: | ||
original_metadata.append(cls._metadata) | ||
custom_metadata = cls._metadata.copy() | ||
custom_metadata.append("attr") | ||
|
||
monkeypatch.setattr(cls, "_metadata", custom_metadata) | ||
|
||
|
||
@pytest.mark.usefixtures("custom_meta") | ||
def test_custom_finalizer(): | ||
|
||
df = pd.DataFrame({"A": [1, 2]}) | ||
df.attr = 0 | ||
|
||
result = df.copy() | ||
assert result.attr == 1 | ||
|
||
|
||
@pytest.mark.usefixtures("custom_meta") | ||
def test_concat(): | ||
df1 = pd.DataFrame({"A": [1, 2]}) | ||
df1.attr = 2 | ||
|
||
df2 = pd.DataFrame({"A": [1, 2]}) | ||
df2.attr = 3 | ||
|
||
result = pd.concat([df1, df2]) | ||
assert result.attr == 5 |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do you have an implementation for index_allows_duplicates? I'd be more comfortable if there were a more fully fleshed-out example/test.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hmm, I thought I did but am having trouble finding it right now.