Skip to content

feat: add as_series flag to maybe_get_index to return the index as a narwhals Series#3706

Open
mvanhorn wants to merge 1 commit into
narwhals-dev:mainfrom
mvanhorn:feat/3693-maybe-get-index-as-series
Open

feat: add as_series flag to maybe_get_index to return the index as a narwhals Series#3706
mvanhorn wants to merge 1 commit into
narwhals-dev:mainfrom
mvanhorn:feat/3693-maybe-get-index-as-series

Conversation

@mvanhorn

Copy link
Copy Markdown

Description

Add a keyword-only as_series: bool = False argument to maybe_get_index. When as_series=True and the input is pandas-like, the index is returned wrapped as a narwhals Series (matching the input's implementation and stable-api version) instead of the raw native index. The default behavior is unchanged: as_series=False returns the raw native index, and non-pandas-like inputs return None.

This closes the request in #3693. maybe_get_index previously returned the raw pandas-like Index, which cannot be fed directly into maybe_set_index(..., index=...) because that parameter expects a narwhals Series (or list of them). Callers had to drop down to native objects and reassign .index by hand. With as_series=True, the result round-trips straight into maybe_set_index:

new_series = nw.maybe_set_index(new_series, index=nw.maybe_get_index(like, as_series=True))

Backend parity is preserved: the returned Series carries the same implementation as the input (pandas / modin / cuDF), and the stable v1 / v2 namespaces return their own Series type. Non-pandas-like inputs (e.g. Polars) still return None rather than an empty Series.

What type of PR is this? (check all applicable)

  • 💾 Refactor
  • ✨ Feature
  • 🐛 Bug Fix
  • 🔧 Optimization
  • 📝 Documentation
  • ✅ Test
  • 🐳 Other

Related issues

Checklist

  • Code follows style guide (ruff)
  • Tests added
  • Documented the changes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add argument in maybe_get_index to return the index as narwhals Series

1 participant