Skip to content

Commit

Permalink
fix(python): preserve Series name when exporting to pandas (#5498)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexander-beedie committed Nov 14, 2022
1 parent a01b8a7 commit 8210a27
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
6 changes: 4 additions & 2 deletions py-polars/polars/internals/series/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -2724,10 +2724,12 @@ def to_pandas(self) -> pd.Series:
0 1
1 2
2 3
dtype: int64
Name: a, dtype: int64
"""
return self.to_arrow().to_pandas()
pd_series = self.to_arrow().to_pandas()
pd_series.name = self.name
return pd_series

def set(self, filter: Series, value: int | float | str) -> Series:
"""
Expand Down
21 changes: 21 additions & 0 deletions py-polars/tests/unit/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,27 @@ def test_cast() -> None:
pl.Series(["1", "2", "3", "4", "foobar"]).cast(int)


def test_to_pandas() -> None:
for test_data in (
[1, None, 2],
["abc", None, "xyz"],
[None, datetime.now()],
[[1, 2], [3, 4], None],
):
a = pl.Series("s", test_data)
b = a.to_pandas()

assert a.name == b.name
assert b.isnull().sum() == 1

if a.dtype == pl.List:
cvals = [(None if x is None else x.tolist()) for x in b]
assert cvals == test_data
else:
c = b.replace({np.nan: None})
assert c.values.tolist() == test_data # type: ignore[union-attr]


def test_to_python() -> None:
a = pl.Series("a", range(20))
b = a.to_list()
Expand Down

0 comments on commit 8210a27

Please sign in to comment.