-
Notifications
You must be signed in to change notification settings - Fork 210
feat: add nw.factorize #3809
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
camriddell
wants to merge
13
commits into
narwhals-dev:main
Choose a base branch
from
camriddell:feat-factorize
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
feat: add nw.factorize #3809
Changes from 3 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
d38d4cb
feat: add nw.factorize
camriddell dfcc905
factorize test skip Polars < 1.0 due to lack of replace_strict
camriddell 9a5dacf
add factorize test for nw V2
camriddell 7d8459a
fix: nw.factorize doctest & docstring returns
camriddell 8b798aa
ref: move factorize to Series method & make specific for each backend
camriddell e3b4cb4
perf: pyarrow factorize fastpath
camriddell e8d73e9
perf: polars factorize pass native series instead of .to_list
camriddell 2abe03d
feat: add null_as_value to factorize
camriddell 9d7a132
ref: factorize overwrite result names to "codes" and "uniques"
camriddell 44c3b55
ref: factorize to produce Namedtuple result
camriddell 571ce63
Merge branch 'main' of https://github.com/narwhals-dev/narwhals into …
camriddell f6510a0
ref: factorize: namedtuple -> dataclass to avoid multiple inheritance
camriddell fa085fd
fix v1/v2 factorize tests with new column names
camriddell File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,124 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from math import isnan | ||
| from typing import Any | ||
|
|
||
| import pytest | ||
|
|
||
| import narwhals as nw | ||
| from tests.utils import ( | ||
| POLARS_VERSION, | ||
| ConstructorEager, | ||
| assert_equal_data, | ||
| assert_equal_series, | ||
| ) | ||
|
|
||
| polars_lt_v1 = POLARS_VERSION < (1, 0, 0) | ||
| pl_skip_reason = "replace_strict only available after 1.0" | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| ("values", "expected_n_unique"), | ||
| [ | ||
| ([], 0), | ||
| ([*"abcabc"], 3), | ||
| ([1, 2, 3, 2], 3), | ||
| ([1.1, 2.2, 3.3, 2.2], 3), | ||
| ([*"abc", None], 3), | ||
| ([*"aaabbbccc", None], 3), | ||
| ], | ||
| ) | ||
| def test_factorize_invariants( | ||
| values: list[Any], expected_n_unique: int, constructor_eager: ConstructorEager | ||
| ) -> None: | ||
| if "polars" in str(constructor_eager) and polars_lt_v1: | ||
| pytest.skip(reason=pl_skip_reason) | ||
|
|
||
| has_null = any(x is None for x in values) | ||
|
|
||
| df_native = constructor_eager({"a": values}) | ||
| df = nw.from_native(df_native) | ||
| codes, uniqs = nw.factorize(df["a"]) | ||
|
|
||
| reconstructed_values = {"a": [uniqs[i] if i >= 0 else None for i in codes]} | ||
| assert_equal_data(df, reconstructed_values) | ||
| assert uniqs.dtype == df["a"].dtype | ||
| assert len(uniqs) == expected_n_unique | ||
|
|
||
| # codes should be integer, preserve length, and only contain -1 in the presence of nulls | ||
| assert codes.dtype.is_integer() | ||
| assert len(codes) == len(values) | ||
| assert (codes >= -1).all() | ||
| assert (codes == -1).any() == has_null | ||
|
|
||
| # Null values should always be dropped out from the unique returned values | ||
| assert not (uniqs.is_null().any()) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| ("values", "expected_uniqs", "expected_codes"), | ||
| [ | ||
| ([], [], []), | ||
| ([*"abc"], [*"abc"], [0, 1, 2]), | ||
| ([*"abcabc"], [*"abc"], [0, 1, 2, 0, 1, 2]), | ||
| ([*"aaabbbccc"], [*"abc"], [0, 0, 0, 1, 1, 1, 2, 2, 2]), | ||
| ([*"abcabc", None], [*"abc"], [0, 1, 2, 0, 1, 2, -1]), | ||
| ], | ||
| ) | ||
| def test_factorize_sort( | ||
| values: list[Any], | ||
| expected_uniqs: list[Any], | ||
| expected_codes: list[int], | ||
| constructor_eager: ConstructorEager, | ||
| ) -> None: | ||
| if "polars" in str(constructor_eager) and polars_lt_v1: | ||
| pytest.skip(reason=pl_skip_reason) | ||
|
|
||
| df_native = constructor_eager({"a": values}) | ||
| df = nw.from_native(df_native) | ||
| codes, uniqs = nw.factorize(df["a"], sort=True) | ||
|
|
||
| assert_equal_series(uniqs, expected_uniqs, name="a") | ||
| assert_equal_series(codes, expected_codes, name="a") | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "values", | ||
| [ | ||
| [1.1, 2.2, 1.1, float("nan")], | ||
| [1.1, 2.2, 1.1, float("nan"), float("nan")], | ||
| [1.1, 2.2, 1.1, None, float("nan")], | ||
| ], | ||
| ) | ||
| def test_factorize_nan_semantics( | ||
| values: list[float], constructor_eager: ConstructorEager | ||
| ) -> None: | ||
| if "polars" in str(constructor_eager) and polars_lt_v1: | ||
| pytest.skip(reason=pl_skip_reason) | ||
|
|
||
| is_pandas_backend = any(x in str(constructor_eager) for x in ("pandas", "modin")) | ||
|
|
||
| df_native = constructor_eager({"a": values}) | ||
| df = nw.from_native(df_native) | ||
| codes, uniqs = nw.factorize(df["a"]) | ||
|
|
||
| reconstructed_values = {"a": [uniqs[i] if i >= 0 else None for i in codes]} | ||
| assert_equal_data(df, reconstructed_values) | ||
|
|
||
| if is_pandas_backend: | ||
| # pandas treats NaN as missing, so NaN is not retained as a unique value. | ||
| assert len(uniqs) == 2 | ||
| assert (codes == -1).any() | ||
| assert not uniqs.is_null().any() | ||
| else: | ||
| # Other backends treat NaN as a value, not as null. | ||
| assert len(uniqs) == 3 | ||
|
|
||
| # The NaN should round-trip through codes -> uniques. | ||
| nan_index = ( | ||
| i | ||
| for i, value in enumerate(values) | ||
| if isinstance(value, float) and isnan(value) | ||
| ) | ||
| nan_codes = (codes[nan_i] for nan_i in nan_index) | ||
| assert all(isnan(uniqs[nan_c]) for nan_c in nan_codes) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -586,3 +586,33 @@ def test_schema_from_generator() -> None: | |
| ) | ||
| assert schema == nw_v2.Schema({"a": nw_v2.Int64(), "b": nw_v2.String()}) | ||
| assert schema._version is Version.V2 | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Per the other comments, if |
||
| ("values", "expected_uniqs", "expected_codes"), | ||
| [ | ||
| ([], [], []), | ||
| ([*"abc"], [*"abc"], [0, 1, 2]), | ||
| ([*"abcabc"], [*"abc"], [0, 1, 2, 0, 1, 2]), | ||
| ([*"aaabbbccc"], [*"abc"], [0, 0, 0, 1, 1, 1, 2, 2, 2]), | ||
| ([*"abcabc", None], [*"abc"], [0, 1, 2, 0, 1, 2, -1]), | ||
| ], | ||
| ) | ||
| def test_factorize( | ||
| values: list[Any], | ||
| expected_uniqs: list[Any], | ||
| expected_codes: list[int], | ||
| constructor_eager: ConstructorEager, | ||
| ) -> None: | ||
| if "polars" in str(constructor_eager) and (POLARS_VERSION < (1, 0, 0)): | ||
| pytest.skip(reason="replace_strict only available after 1.0") | ||
|
|
||
| df_native = constructor_eager({"a": values}) | ||
| df = nw_v2.from_native(df_native) | ||
| codes, uniqs = nw_v2.factorize(df["a"], sort=True) | ||
|
|
||
| assert_equal_series(uniqs, expected_uniqs, name="a") | ||
| assert_equal_series(codes, expected_codes, name="a") | ||
|
|
||
| assert codes._version is Version.V2 | ||
| assert uniqs._version is Version.V2 | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.