From a8fa1de34988725e27d713097cbc2ab4b1aa1c63 Mon Sep 17 00:00:00 2001 From: Tom Augspurger Date: Tue, 7 Jan 2020 16:06:20 -0600 Subject: [PATCH] API: Store name outside attrs This aligns with xarray and h5py: https://github.com/pandas-dev/pandas/pull/29062#issuecomment-545703586 --- pandas/core/series.py | 7 ++++--- pandas/tests/frame/test_api.py | 8 ++++++++ pandas/tests/series/test_api.py | 7 +++++++ 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/pandas/core/series.py b/pandas/core/series.py index b81659920cfe8..c968d06852d42 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -159,7 +159,8 @@ class Series(base.IndexOpsMixin, generic.NDFrame): _typ = "series" - _metadata: List[str] = [] + _name: Hashable + _metadata: List[str] = ["name"] _accessors = {"dt", "cat", "str", "sparse"} _deprecations = ( base.IndexOpsMixin._deprecations @@ -425,13 +426,13 @@ def dtypes(self): @property def name(self) -> Optional[Hashable]: - return self.attrs.get("name", None) + return self._name @name.setter def name(self, value: Optional[Hashable]) -> None: if not is_hashable(value): raise TypeError("Series.name must be a hashable type") - self.attrs["name"] = value + object.__setattr__(self, "_name", value) @property def values(self): diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py index 26d6a917fe1ca..9263409f7a7f8 100644 --- a/pandas/tests/frame/test_api.py +++ b/pandas/tests/frame/test_api.py @@ -551,3 +551,11 @@ async def test_tab_complete_warning(self, ip): with tm.assert_produces_warning(None): with provisionalcompleter("ignore"): list(ip.Completer.completions("df.", 1)) + + def test_attrs(self): + df = pd.DataFrame({"A": [2, 3]}) + assert df.attrs == {} + df.attrs["version"] = 1 + + result = df.rename(columns=str) + assert result.attrs == {"version": 1} diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py index d235e51d00793..f96d6ddfc357e 100644 --- a/pandas/tests/series/test_api.py +++ b/pandas/tests/series/test_api.py @@ -512,6 +512,13 @@ def test_integer_series_size(self): s = Series(range(9), dtype="Int64") assert s.size == 9 + def test_attrs(self): + s = pd.Series([0, 1], name="abc") + assert s.attrs == {} + s.attrs["version"] = 1 + result = s + 1 + assert result.attrs == {"version": 1} + class TestCategoricalSeries: @pytest.mark.parametrize(