Skip to content

Commit

Permalink
feat: add Series.to_list (#345)
Browse files Browse the repository at this point in the history
* feat: add Series.to_list

* add test
  • Loading branch information
MarcoGorelli authored Jun 28, 2024
1 parent e548d6d commit 30bba15
Show file tree
Hide file tree
Showing 5 changed files with 47 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/api-reference/series.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
- sum
- tail
- to_frame
- to_list
- to_numpy
- to_pandas
- unique
Expand Down
3 changes: 3 additions & 0 deletions narwhals/_pandas_like/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
27 changes: 27 additions & 0 deletions narwhals/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
15 changes: 15 additions & 0 deletions tests/series/to_list_test.py
Original file line number Diff line number Diff line change
@@ -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]
1 change: 1 addition & 0 deletions utils/check_api_reference.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@
.difference(
{
"to_pandas",
"to_list",
"to_numpy",
"dtype",
"name",
Expand Down

0 comments on commit 30bba15

Please sign in to comment.