From 30bba1506ee7c4a2cb874ceceac7a898a2eba8e7 Mon Sep 17 00:00:00 2001 From: Marco Edward Gorelli Date: Fri, 28 Jun 2024 10:56:27 +0100 Subject: [PATCH] feat: add Series.to_list (#345) * feat: add Series.to_list * add test --- docs/api-reference/series.md | 1 + narwhals/_pandas_like/series.py | 3 +++ narwhals/series.py | 27 +++++++++++++++++++++++++++ tests/series/to_list_test.py | 15 +++++++++++++++ utils/check_api_reference.py | 1 + 5 files changed, 47 insertions(+) create mode 100644 tests/series/to_list_test.py diff --git a/docs/api-reference/series.md b/docs/api-reference/series.md index f1d2ddfc9..2687eead5 100644 --- a/docs/api-reference/series.md +++ b/docs/api-reference/series.md @@ -42,6 +42,7 @@ - sum - tail - to_frame + - to_list - to_numpy - to_pandas - unique diff --git a/narwhals/_pandas_like/series.py b/narwhals/_pandas_like/series.py index 09d9ea569..1ea029d0b 100644 --- a/narwhals/_pandas_like/series.py +++ b/narwhals/_pandas_like/series.py @@ -180,6 +180,9 @@ def to_frame(self) -> Any: self._series.to_frame(), implementation=self._implementation ) + def to_list(self) -> Any: + return self._series.to_list() + def is_between( self, lower_bound: Any, upper_bound: Any, closed: str = "both" ) -> PandasSeries: diff --git a/narwhals/series.py b/narwhals/series.py index 8e68ee2dd..b892053bc 100644 --- a/narwhals/series.py +++ b/narwhals/series.py @@ -301,6 +301,33 @@ def to_frame(self) -> DataFrame: return DataFrame(self._series.to_frame()) + def to_list(self) -> list[Any]: + """ + Convert to list. + + Examples: + >>> import pandas as pd + >>> import polars as pl + >>> import narwhals as nw + >>> s = [1, 2, 3] + >>> s_pd = pd.Series(s, name="a") + >>> s_pl = pl.Series("a", s) + + We define a library agnostic function: + + >>> @nw.narwhalify + ... def func(s_any): + ... return s_any.to_list() + + We can then pass either pandas or Polars to `func`: + + >>> func(s_pd) + [1, 2, 3] + >>> func(s_pl) + [1, 2, 3] + """ + return self._series.to_list() # type: ignore[no-any-return] + def mean(self) -> Any: """ Reduce this Series to the mean value. diff --git a/tests/series/to_list_test.py b/tests/series/to_list_test.py new file mode 100644 index 000000000..c17b4f144 --- /dev/null +++ b/tests/series/to_list_test.py @@ -0,0 +1,15 @@ +from typing import Any + +import pandas as pd +import polars as pl +import pytest + +import narwhals as nw + +data = [1, 2, 3] + + +@pytest.mark.parametrize("constructor", [pd.Series, pl.Series]) +def test_to_list(constructor: Any) -> None: + s = nw.from_native(constructor(data), series_only=True) + assert s.to_list() == [1, 2, 3] diff --git a/utils/check_api_reference.py b/utils/check_api_reference.py index 44d81ffbd..b40b55ad6 100644 --- a/utils/check_api_reference.py +++ b/utils/check_api_reference.py @@ -145,6 +145,7 @@ .difference( { "to_pandas", + "to_list", "to_numpy", "dtype", "name",