diff --git a/narwhals/_pandas_like/series.py b/narwhals/_pandas_like/series.py index 20b5947ed..39130b191 100644 --- a/narwhals/_pandas_like/series.py +++ b/narwhals/_pandas_like/series.py @@ -1170,7 +1170,18 @@ def len(self: Self) -> PandasLikeSeries: from narwhals.utils import import_dtypes_module native_series = self._compliant_series._native_series - native_result = native_series.list.len().rename(native_series.name, copy=False) + native_result = native_series.list.len() + + if ( + self._compliant_series._implementation is Implementation.PANDAS + and self._compliant_series._backend_version < (3, 0) + ): # pragma: no cover + native_result = set_axis( + native_result.rename(native_series.name, copy=False), + index=native_series.index, + implementation=self._compliant_series._implementation, + backend_version=self._compliant_series._backend_version, + ) dtype = narwhals_to_native_dtype( dtype=import_dtypes_module(self._compliant_series._version).UInt32(), starting_dtype=native_result.dtype, diff --git a/tests/expr_and_series/list/len_test.py b/tests/expr_and_series/list/len_test.py index 06dc0d936..7066fc6cf 100644 --- a/tests/expr_and_series/list/len_test.py +++ b/tests/expr_and_series/list/len_test.py @@ -1,5 +1,6 @@ from __future__ import annotations +import pandas as pd import pytest import narwhals.stable.v1 as nw @@ -43,3 +44,15 @@ def test_len_series( result = df["a"].cast(nw.List(nw.Int32())).list.len() assert_equal_data({"a": result}, expected) + + +def test_pandas_preserve_index(request: pytest.FixtureRequest) -> None: + if PANDAS_VERSION < (2, 2): + request.applymarker(pytest.mark.xfail) + + index = pd.Index(["a", "b", "c", "d", "e"]) + df = nw.from_native(pd.DataFrame(data, index=index), eager_only=True) + + result = df["a"].cast(nw.List(nw.Int32())).list.len() + assert_equal_data({"a": result}, expected) + assert (result.to_native().index == index).all()