Skip to content

ENH add narwhals as dependency - #31127

Merged
adrinjalali merged 22 commits into
scikit-learn:mainfrom
lorentzenchr:narwhals
May 7, 2026
Merged

adrinjalali merged 22 commits into
scikit-learn:mainfrom
lorentzenchr:narwhals

Conversation

@lorentzenchr

@lorentzenchr lorentzenchr commented Apr 1, 2025 •

Copy link
Copy Markdown
Member

Reference Issues/PRs

Closes #31049.

What does this implement/fix? Explain your changes.

This PR adds narwhals as runtime dependency like joblib and uses narwhals in:

  • _safe_indexing

Edit: It now replaces any use and mention of __dataframe__ interchange protocol.

Any other comments?

Not yet.

@lorentzenchr
lorentzenchr marked this pull request as draft April 1, 2025 21:32
@github-actions

github-actions Bot commented Apr 1, 2025 •

Copy link
Copy Markdown

✔️ Linting Passed

All linting checks passed. Your pull request is in excellent shape! ☀️

Generated for commit: f5a0700. Link to the linter CI: here

Comment on lines 264 to +277
if hasattr(X, "iloc"):
# TODO: we should probably use _is_pandas_df_or_series(X) instead but this
# would require updating some tests such as test_train_test_split_mock_pandas.
# TODO: Should also work with _narwhals_indexing, but
# test_safe_indexing_pandas_no_settingwithcopy_warning
# does not pass.
return _pandas_indexing(X, indices, indices_dtype, axis=axis)
elif _is_polars_df_or_series(X):
return _polars_indexing(X, indices, indices_dtype, axis=axis)
elif nw.dependencies.is_into_dataframe(X) or nw.dependencies.is_into_series(X):
return _narwhals_indexing(X, indices, indices_dtype, axis=axis)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This whole section should read

    if nw.dependencies.is_into_dataframe(X) or nw.dependencies.is_into_series(X):
        return _narwhals_indexing(X, indices, indices_dtype, axis=axis)

and the pandas/iloc path should be removed. But currently, it does not pass the test test_safe_indexing_pandas_no_settingwithcopy_warning.

@MarcoGorelli You might have additional insights.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks for the ping, i'll take a look next week!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To be honest I don't understand this test. It checks that pandas makes a copy, but only when indexing with [0, 1]. On the main branch, changing that to slice(0, 2) is enough to make the test fail

I'll open a separate issue to discuss

Narwhals objects (DataFrame, Series) are immutable so this isn't something you should need to worry about with Narwhals anyway

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here you go: #31290

Anyone in particular we should tag in it?

@adrinjalali

Copy link
Copy Markdown
Member

I'd be happy to see us adopting narwhals, using narwhals.stable.v2. @lorentzenchr do you think you could drive this? I know it can be a long road.

@MarcoGorelli

Copy link
Copy Markdown
Contributor

@adrinjalali do you have thoughts on #31290? I think we'd need to align on what the desired behaviour is there

@lorentzenchr

Copy link
Copy Markdown
Member Author

do you think you could drive this?

Yes, I can, but that's not the main problem: It needs community support (from scikit-learn and narwhals) and we (scikit-learn) need to assess whether it is worth it. I first thought, yeah let't do it. But the more failures I fixed, the more I thought about pros and cons. The better place for those is in the original issue #31049.

@MarcoGorelli

Copy link
Copy Markdown
Contributor

ok i see what's happening, will make a PR to your branch

@MarcoGorelli

Copy link
Copy Markdown
Contributor

Alright here we go: lorentzenchr#9

Issues I spotted:

  • The main one is that pyarrow.Array doesn't go down the _narwhals_indexing path. This is because nw.Series is backed by pyarrow.ChunkedArray, not pyarrow.Array. So, we need to temporarily convert to ChunkedArray to be able to re-use the same path
  • nw.DataFrame.row, for PyArrow, currently returns a tuple of Arrow scalars, rather than of Python scalars. We've determined that this a bug/oversight in Narwhals, and will fix it, but for compatibility with older versions, I've presented a simple workaround using iter_columns and item
  • nw.DataFrame.__getitem__ doesn't explicitly support boolean masks, so it happens to work for pandas/Polars but raises an error for PyArrow. We've agreed that we'll explicitly support/document/test this too, but again for compatibility with older versions I've presented a simple workaround using select

If you're happy to keep a separate pandas path, then I agree that #31290 isn't actually a blocker 👍

@adrinjalali adrinjalali left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shallow-ish review, generally I love this!

Comment thread sklearn/compose/_column_transformer.py Resolved
return array[key, ...] if axis == 0 else array[:, key]


def _narwhals_indexing(X, key, key_dtype, axis):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does this look good to you @MarcoGorelli ?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yup! i'd taken a look and had pushed https://github.com/lorentzenchr/scikit-learn/pull/9/changes

i know @FBruzzesi and @EdAbati were also interested in this, so cc-ing them here in case they have comments


# Narwhals Series are backed by ChunkedArray, not Array.
# To reuse `_narwhals_indexing`, we temporarily convert to `ChunkedArray`.
pa = sys.modules["pyarrow"]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we have CI w/ and w/o it?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I think so. test_safe_indexing_1d_container is parametrized with "pyarrow_array".

@lorentzenchr

lorentzenchr commented Apr 27, 2026 •

Copy link
Copy Markdown
Member Author

FYI: Narwhals has no dependencies, so I set the minimum version to the current 2.20, we use narwhals.stable.v2 so it set the minimum version to narwhals 2.0.1.

@thomasjpfan thomasjpfan left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall, I'm slightly more in favor of adding narwhals as a dependency compared to vendoring.

c.dtype[0].name == "CATEGORICAL"
for c in X.__dataframe__().get_columns()
]
[d in (nw.Categorical, nw.Enum) for d in dtypes]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For Polars, does this open up support for pl.Enum? If so, do we have a test for it?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

df_polars.__dataframe__() set Enum columns to categorical in the interchange format, so no changed behavior, see #33789 (comment).

# TODO: `X_indexed` is a DataFrame with a single row; we return a Series to be
# consistent with pandas. Narwhals would return a dataframe which is
# advantageous if the columns have different dtypes.
return np.array([col.item(0) for col in X_indexed.iter_columns()])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

According to the comment, should the return type be a Series and not a NumPy array?

@lorentzenchr lorentzenchr May 2, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning

rabbit hole

I would prefer a dataframe with a single row because it preserves all the dtypes of the columns. What we do here can mix columns and might result in something like np.array([0, 1, "a", "b", date(2000, 1, 14)]). A schau single row df would have shape (1, n_features)` and the indexing on an array would have shape (n_features,). It is a tradeoff.

Comment thread sklearn/utils/_indexing.py Outdated
Comment on lines +77 to +78
if key_dtype in ("bool", "str") and not isinstance(key, (list, slice)):
key = key.tolist()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I am just reading this if condition, it does not guarantee that key is a NumPy array with a tolist API.

I do not see it immediately, but is there a way to make the "normalization" of key easier to understand?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is guaranteed to be an array. Read just a few lines before it, there is another if-condition. I don't know why I reverted the order, but it includes the same check.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I simplified it in 4867f5c, relying mainly on the available tests.



@pytest.mark.parametrize("constructor_name", ["dataframe", "polars"])
@pytest.mark.parametrize("constructor_name", ["pandas", "polars"])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Finally, we are renaming dataframe -> pandas 🎉

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Only I did, in this instance 😏

@lorentzenchr

Copy link
Copy Markdown
Member Author

@adrinjalali @thomasjpfan I think I addressed all your comments. CI is green. Review approvals would be welcome.

@thomasjpfan

Copy link
Copy Markdown
Member

Code-wise this looks good to me. My biggest concern is the new dependency on narwhals. Is there consensus with adding a new dependency to scikit-learn?

@lorentzenchr

lorentzenchr commented May 7, 2026 •

Copy link
Copy Markdown
Member Author

Code-wise this looks good to me. My biggest concern is the new dependency on narwhals. Is there consensus with adding a new dependency to scikit-learn?

Yes, there seems to be consensus for adding it as dependency. We discussed in in the last monthly meeting. It is a very light dependency: Narwhals only depends on Python.

@adrinjalali

Copy link
Copy Markdown
Member

Yeah we've discussed this a few times in the meetings, and there's been no objection and with stable.v2 we seem to be happy to have the dependency (I'm still not sure about the exceptions import outside stable v2 though). But I think better merge this to have it tested a bit before the upcoming release. I'll send out an email to the mailing list about this.

@adrinjalali
adrinjalali merged commit 8c62b6b into scikit-learn:main May 7, 2026
33 checks passed
@lorentzenchr

Copy link
Copy Markdown
Member Author

Thanks to all participants, in particular the reviewers and @MarcoGorelli for his support and for closing gaps in narwhals.

@FBruzzesi

FBruzzesi commented May 10, 2026 •

Copy link
Copy Markdown

Hey everyone, and happy Sunday 👋🏼

First of all, it's amazing to see this PR landing 🤩

Note

Commenting it here to avoid opening a dedicated issue for now. Happy to do so if this needs more visibility

In Narwhals we take some effort to make sure that what we release/merge does not end up breaking downstream libraries that use Narwhals. We run tests of these libraries as part of our usual CI with Narwhals installing from the PR codebase (see downstream_tests.yaml).

For some libraries, these test might take a while and we end up running only specific tests (see darts example).
In a way this is a hack which might break easily in (at least) the following two scenarios:

  • A test is moved -> breaks our CI (happened with plotly)
  • A new test is added and we don't run it -> silent "failure"

I would consider scikit-learn to be among the libraries which tests can be quite long in their entirety (~10 minutes, see narwhals-dev/narwhals#3609)

If there is a clear subset of tests that would be enough for us to run, one way to do it would be by adding a pytestmark = pytest.mark.narwhals at the top of the test files that run with Narwhals.
In this way we simply run pytest -m narwhals to collect all and only these tests, without the need to change it over time (from our perspective).

Let me know if this is a viable idea.


Example from fairlearn: fairlearn/fairlearn#1597

@lorentzenchr

Copy link
Copy Markdown
Member Author

If there is a clear subset of tests

So far, all of narwhals usage is contained within

  • sklearn.compose._column_transformer -> sklearn/compose/test/test_column_transformer
  • sklearn.ensemble._histgradient_boosting.gradient_boosting -> sklearn/ensemble/_histgradient_boosting/tests.gradient_boosting.py
  • sklearn.utils._indexing -> sklearn/utils/tests/test_indexing.py
  • sklearn.utils.validation -> sklearn/utils/tests/test_validation.py

The last 2 are the most important ones.

@lorentzenchr

Copy link
Copy Markdown
Member Author

@MarcoGorelli @adrinjalali @jeremiedbb Could someone add @MarcoGorelli as co-author in the release notes? I forgot that and without him, it would not have been merged.

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.

RFC adopt narwhals for dataframe support

5 participants