Skip to content

[Data] Add drop parameter to OneHotEncoder and MultiHotEncoder - #60533

Closed
slfan1989 wants to merge 5 commits into
ray-project:masterfrom
slfan1989:data/encoder-drop-parameter
Closed

slfan1989 wants to merge 5 commits into
ray-project:masterfrom
slfan1989:data/encoder-drop-parameter

Conversation

@slfan1989

@slfan1989 slfan1989 commented Jan 27, 2026 •

Copy link
Copy Markdown
Contributor

Description

This PR adds a drop parameter to OneHotEncoder and MultiHotEncoder preprocessors to help prevent multicollinearity when using one-hot encoded features in linear models.

Key improvements:

  • Adds optional drop parameter with three strategies: None (default), "first", and "if_binary"
  • Implements drop logic for both Pandas and Arrow execution paths
  • Aligns Ray Data's encoder API with scikit-learn's OneHotEncoder design
  • Resolves the TODO comment in MultiHotEncoder.init

Related issues

Related to the TODO comment in python/ray/data/preprocessors/encoder.py:657

Additional information

API Changes
Both OneHotEncoder and MultiHotEncoder now accept a drop parameter:

def __init__(
        self,
        columns: List[str],
        *,
        max_categories: Optional[Dict[str, int]] = None,
        drop: Optional[Literal["first", "if_binary"]] = None,  # NEW
        output_columns: Optional[List[str]] = None,
):

Parameter behavior:

  • drop=None (default): Retains all categories (backward compatible)
  • drop="first": Always drops the first category (alphabetically)
  • drop="if_binary": Drops first category only when exactly 2 categories exist

Implementation Details

OneHotEncoder changes:

  • Modified _transform_pandas() to apply drop logic after one-hot encoding
  • Modified _encode_column_one_hot() to handle drop in Arrow execution path
  • Updated _get_serializable_fields() and _set_serializable_fields()
  • Updated repr() to display drop parameter
  • Added comprehensive docstring documentation

MultiHotEncoder changes:

  • Modified _transform_pandas() to apply drop logic using lambda functions
  • Updated serialization methods and repr()
  • Removed TODO comment
  • Added comprehensive docstring documentation

@slfan1989
slfan1989 requested a review from a team as a code owner January 27, 2026 11:12

@gemini-code-assist gemini-code-assist Bot left a comment

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.

Code Review

This pull request introduces a drop parameter to OneHotEncoder and MultiHotEncoder, aligning their API with scikit-learn's design and addressing multicollinearity concerns. The implementation correctly handles None, "first", and "if_binary" drop strategies for both Pandas and Arrow execution paths. The addition of comprehensive test cases for various scenarios, including unknown categories, ensures the robustness and correctness of the new functionality. This is a valuable enhancement for the preprocessors.

@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Jan 27, 2026
@slfan1989
slfan1989 force-pushed the data/encoder-drop-parameter branch 2 times, most recently from 68460a2 to 8339108 Compare February 27, 2026 20:54
@slfan1989

Copy link
Copy Markdown
Contributor Author

@xinyuangui2 drop the first alphabetical column means: after sorting the categories, treat the one that comes first in the sorted order as the reference (baseline) category and drop its corresponding column. This is done simply to establish a stable and reproducible rule. In essence, which column gets dropped is arbitrary—the model's predictive performance remains unchanged; only the interpretation of the coefficients will differ depending on which category is chosen as the baseline.

@slfan1989
slfan1989 force-pushed the data/encoder-drop-parameter branch from 4cd3af4 to 508ff80 Compare March 8, 2026 13:18
@slfan1989
slfan1989 force-pushed the data/encoder-drop-parameter branch from 55f26cd to 26df231 Compare March 19, 2026 15:49
@github-actions

github-actions Bot commented Apr 3, 2026

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Apr 3, 2026
This commit adds a `drop` parameter to OneHotEncoder and MultiHotEncoder
to help avoid multicollinearity in machine learning models.

The drop parameter supports:
- None (default): Keep all categories
- "first": Always drop the first category (alphabetically)
- "if_binary": Drop first category only when exactly 2 categories exist

This aligns with sklearn's OneHotEncoder API and addresses the TODO
comment in MultiHotEncoder.__init__.

Changes:
- Add drop parameter to both encoder classes
- Implement drop logic in _transform_pandas methods
- Implement drop logic in _encode_column_one_hot for Arrow backend
- Update serialization methods to include drop field
- Add comprehensive test cases (6 new tests)
- Update documentation with drop parameter details

Signed-off-by: slfan1989 <[email protected]>
@slfan1989
slfan1989 force-pushed the data/encoder-drop-parameter branch from 99aeb63 to f5fba2a Compare April 12, 2026 12:10
@github-actions github-actions Bot added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Apr 12, 2026
@xinyuangui2

Copy link
Copy Markdown
Contributor

Sorry didn't see this earlier. Can we fix the build and I will do another pass. Thanks.

@slfan1989

Copy link
Copy Markdown
Contributor Author

Sorry didn't see this earlier. Can we fix the build and I will do another pass. Thanks.

@xinyuangui2 Thank you for your message! I’ll continue following up on this PR.

slfan1989 and others added 3 commits April 14, 2026 10:22
This commit adds a `drop` parameter to OneHotEncoder and MultiHotEncoder
to help avoid multicollinearity in machine learning models.

The drop parameter supports:
- None (default): Keep all categories
- "first": Always drop the first category (alphabetically)
- "if_binary": Drop first category only when exactly 2 categories exist

This aligns with sklearn's OneHotEncoder API and addresses the TODO
comment in MultiHotEncoder.__init__.

Changes:
- Add drop parameter to both encoder classes
- Implement drop logic in _transform_pandas methods
- Implement drop logic in _encode_column_one_hot for Arrow backend
- Update serialization methods to include drop field
- Add comprehensive test cases (6 new tests)
- Update documentation with drop parameter details

Signed-off-by: slfan1989 <[email protected]>
This commit adds a `drop` parameter to OneHotEncoder and MultiHotEncoder
to help avoid multicollinearity in machine learning models.

The drop parameter supports:
- None (default): Keep all categories
- "first": Always drop the first category (alphabetically)
- "if_binary": Drop first category only when exactly 2 categories exist

This aligns with sklearn's OneHotEncoder API and addresses the TODO
comment in MultiHotEncoder.__init__.

Changes:
- Add drop parameter to both encoder classes
- Implement drop logic in _transform_pandas methods
- Implement drop logic in _encode_column_one_hot for Arrow backend
- Update serialization methods to include drop field
- Add comprehensive test cases (6 new tests)
- Update documentation with drop parameter details

Signed-off-by: slfan1989 <[email protected]>
@xinyuangui2 xinyuangui2 added the go add ONLY when ready to merge, run all tests label Apr 14, 2026
one_hot_matrix[valid_indices, indices_np[valid_mask]] = 1

# Apply drop logic if specified
if self.drop is not None:

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.

ditto

# Drop first only if binary
one_hot = one_hot[:, 1:]

df[output_column] = one_hot.tolist()

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.

make self.drop == "first" or (self.drop == "if_binary" and num_categories == 2) one helper function. if self.drop is not None: is not needed

if self.drop is not None:
if self.drop == "first":
# Always drop the first category
one_hot_matrix = one_hot_matrix[:, 1:]

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.

Is one_hot_matrix sorted here?

elif self.drop == "if_binary" and num_categories == 2:
# Drop first only if binary
one_hot_matrix = one_hot_matrix[:, 1:]
num_categories = num_categories - 1

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.

num_categories -= 1

one_hot_matrix = one_hot_matrix[:, 1:]
num_categories = num_categories - 1

if num_categories == 0:

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.

Do we want to drop only when num_categories > 1?

"""Test OneHotEncoder with drop='first' parameter."""
import pandas as pd

import ray

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.

pandas and ray has been imported already


# With 3 categories and drop='if_binary', should NOT drop (all 3 features)
assert all(len(x) == 3 for x in result_multi["X"])

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.

Maybe also test the num_categories == 1 edge case.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 7295265. Configure here.

one_hot = one_hot[:, 1:]
elif self.drop == "if_binary" and num_categories == 2:
# Drop first only if binary
one_hot = one_hot[:, 1:]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Drop logic duplicated across three transform methods

Low Severity

The drop condition logic (self.drop == "first" or self.drop == "if_binary" and num_categories == 2) is duplicated across OneHotEncoder._transform_pandas, OneHotEncoder._encode_column_one_hot, and MultiHotEncoder._transform_pandas. The outer if self.drop is not None: guard is also redundant since neither inner condition can be true when drop is None. A shared helper (e.g., _should_drop(drop, num_categories)) would reduce duplication and the risk of inconsistent future changes.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 7295265. Configure here.

@bveeramani bveeramani added this to the Data issue and PR backlog milestone Aug 19, 2026
elliot-barn pushed a commit that referenced this pull request Sep 30, 2026
)

## What broke

Calling a preprocessor's `transform_batch` inside a
`map_batches(batch_format="pandas")`
UDF fails on Ray >= 2.56. Three shapes, reported by a user upgrading
from 2.55:

```python
ds = ray.data.from_items([{"n": 1}, {"n": 2}, {"n": 3}, {"n": 4}])
scaler = StandardScaler(columns=["n"]).fit(ds)
ds.map_batches(lambda b: scaler.transform_batch(b), batch_format="pandas").take_all()
```

| input | error |
|---|---|
| int column, `StandardScaler` | `ArrowInvalid: Float value -1.341641
was truncated converting to int64` |
| string column, `OrdinalEncoder` / `OneHotEncoder` | `ValueError:
ArrowStringArray requires a PyArrow (chunked) array of large_string
type` |
| a list column merely *present* in the batch | `TypeError: data type
'list<item: string>[pyarrow]' not understood` |

The third needs no list-typed input to the preprocessor — a `tags`
column sitting
unused in the batch is enough while a float column is scaled.

## Why

`_transform_batch` converted the whole batch with
`pa.Table.from_pandas`, which records
the input dtypes in the table's pandas schema metadata, ran
`_transform_arrow`, and
converted back with `to_pandas`. The transform changes column types —
int64 to double
for a scaler, string to int64 for an ordinal encoding — but the metadata
still described
the input, so the conversion back cast the results to their
pre-transform dtypes.

That round trip landed in 2.54 (#59810). 2.56 (#63017) made pandas
batches Arrow-backed,
which is what made those cast-backs fail. So this is a latent bug that
2.56 exposed
rather than one 2.56 introduced: the same call already failed on 2.55
when handed an
Arrow-backed frame directly.

## The fix

Stop round-tripping the batch. Only the columns the preprocessor reads
(`get_input_columns`) cross into Arrow, without the metadata, and only
the ones it writes
(`get_output_columns`) come back. The result is a shallow copy of the
caller's frame with
those columns replaced, so untouched columns, the index, the axis names
and `attrs` never
leave pandas — there is nothing to rebuild.

- A written column that keeps its Arrow type keeps the dtype of the
column it replaces
  (a scaled `Float64` stays `Float64`).
- Otherwise it keeps that column's backing. An Arrow-backed column stays
Arrow-backed
whatever `enable_arrow_backed_pandas_conversion` says — the flag governs
how Ray
converts its own blocks, not the caller's columns — except for the types
Ray never maps
to an Arrow-backed dtype (extension, dictionary, null), which go through
its block
conversion as before. A NumPy-backed column converts plainly, and a
newly created column
  follows the frame.
- That Arrow-to-pandas type mapping moves unchanged from a closure in
`ArrowBlockAccessor.to_pandas` to module level in `arrow_block.py`, so
both paths share
  one rule.
- A preprocessor that declares no columns falls back to sending the
whole frame.

Writing columns back by position needs `_transform_arrow` to return the
rows it was
given, in order. A changed row count now raises a `ValueError`, and the
`_transform_arrow`
docstring states the contract. All three built-in `_transform_arrow`
implementations are
column transforms and satisfy it.

## Behaviour changes

Both come from untouched columns no longer being re-inferred from Arrow:

- An object column of numbers stays `object`; it used to come back
`int64` / `float64`.
- Integer column labels stay integers; they used to be turned into
strings.

And one for implementers: `_transform_arrow` on a pandas batch now
receives only the
declared input columns, and must not change the rows. The previous code
tolerated a
filtering transform by carrying the index through as a column; it now
raises instead.

## Not a fix for

`enable_arrow_backed_pandas_conversion=False` mitigates this only for
Arrow-block sources.
A pandas block built from an already-Arrow-backed frame — what
`pd.read_parquet(..., dtype_backend="pyarrow")` returns — never
undergoes an
Arrow-to-pandas conversion, so the flag does not reach it; this change
fixes that path.

Two related gaps are left for follow-ups rather than widening this PR:

- `Preprocessor.transform(ds)` has the same stale-metadata defect for a
dataset built from
an Arrow-backed pandas frame with the flag set to `False` (it works with
the default).
- `transform_batch(pa.Table)` returns a table that still carries the
caller's pandas
metadata, so calling `.to_pandas()` on the result can fail the same way.

## Not a duplicate

No open PR touches `_transform_batch` or this pandas/Arrow round trip.
The open
preprocessor work (#66088, #66091) is about how preprocessors are
*fitted* and does not
change the transform path; #60533 adds a `drop` option to the one-hot
encoders in
`encoder.py`. The other open Arrow/pandas PRs are elsewhere: #65539 is
schema
unification for empty datasets, #63938 preserves `CategoricalDtype` in
`Schema.types`.

No open issue covers it either. #64765, the umbrella 2.56 `to_pandas`
regression, is
closed, fixed by #64768 — which added the
`enable_arrow_backed_pandas_conversion`
opt-out and left this round trip untouched.

## Testing

35 `transform_batch` cases added to

`python/ray/data/tests/preprocessors/test_preprocessors_arrow_backed.py`:

- `test_transform_batch_inside_a_pandas_udf` — the three reported
preprocessors through a
  pandas UDF, parametrized over `enable_arrow_backed_pandas_conversion`.
- `test_transform_batch_on_an_arrow_backed_pandas_block` — the shape the
flag does not cover.
- `test_transform_batch_passes_through_an_untouched_list_column` — the
list-column case.
- `test_transform_batch_matches_the_input_backing` /
`..._decides_the_backing_per_column`
— NumPy in gives NumPy out, Arrow in gives Arrow out, and a mixed frame
keeps both.
- `test_transform_batch_keeps_arrow_backing_with_the_flag_off` — the
same holds for all
three preprocessors with `enable_arrow_backed_pandas_conversion=False`.
- `test_transform_batch_keeps_pass_through_extension_dtypes` — nullable
`Int64`, `boolean`
  and `string` columns come back intact, including a value past 2**53.
- `test_transform_batch_leaves_untouched_columns_exactly_as_they_were` —
object columns of
  numbers, a categorical over pandas strings, Python lists.
- `test_transform_batch_preserves_the_index` — named, `MultiIndex` and
tz-aware
  `DatetimeIndex` on both backings, plus the columns axis name.
- `test_transform_batch_keeps_integer_column_labels`,
`..._does_not_modify_the_callers_frame`,
`..._rejects_a_transform_that_changes_the_row_count`,
  `..._on_an_empty_batch`.

The cases assert on values rather than on "did not raise": where the
stale metadata
permitted the cast, the result was silently wrong rather than an error —
an ordinal
encoding coming back as the strings `"0"`, `"1"`, `"2"`.

Against the unmodified source, 21 of the 35 fail:

- 15 are the reported crash on Arrow-backed input.
- 5 are the behaviour changes above: master re-typed untouched object
and categorical
  columns and stringified integer labels.
- 1 is the new contract: master tolerated a filtering
`_transform_arrow`; this raises.

The other 14 pass on master too and are controls — the NumPy-backed
halves, the empty
batch, and the pass-through dtype cases, which guard against a
regression a naive fix
would introduce.

```
$ PYTHONPATH=python/ray/data/tests python -m pytest -q \
    python/ray/data/tests/preprocessors/ --ignore=.../test_torch.py
381 passed, 5 skipped

$ PYTHONPATH=python/ray/data/tests python -m pytest -q python/ray/data/tests/test_arrow_block.py
30 passed
```

The three reported repros were also run end to end through `map_batches`
in Ray workers.
`test_torch.py` is excluded because `torch` is not installed in this
environment; it is
untouched by this change. Pre-commit passes on all three changed files.

Only the declared columns are converted, so wide frames stop paying for
every column:
`StandardScaler(columns=["n"]).transform_batch` on a 1000-column ×
2k-row NumPy frame
goes from ~27 ms to under 1 ms.

AI assistance was used for this change.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Marwan Sarieddine <[email protected]>
Signed-off-by: Aarrya <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Aarrya <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…-project#66578)

## What broke

Calling a preprocessor's `transform_batch` inside a
`map_batches(batch_format="pandas")`
UDF fails on Ray >= 2.56. Three shapes, reported by a user upgrading
from 2.55:

```python
ds = ray.data.from_items([{"n": 1}, {"n": 2}, {"n": 3}, {"n": 4}])
scaler = StandardScaler(columns=["n"]).fit(ds)
ds.map_batches(lambda b: scaler.transform_batch(b), batch_format="pandas").take_all()
```

| input | error |
|---|---|
| int column, `StandardScaler` | `ArrowInvalid: Float value -1.341641
was truncated converting to int64` |
| string column, `OrdinalEncoder` / `OneHotEncoder` | `ValueError:
ArrowStringArray requires a PyArrow (chunked) array of large_string
type` |
| a list column merely *present* in the batch | `TypeError: data type
'list<item: string>[pyarrow]' not understood` |

The third needs no list-typed input to the preprocessor — a `tags`
column sitting
unused in the batch is enough while a float column is scaled.

## Why

`_transform_batch` converted the whole batch with
`pa.Table.from_pandas`, which records
the input dtypes in the table's pandas schema metadata, ran
`_transform_arrow`, and
converted back with `to_pandas`. The transform changes column types —
int64 to double
for a scaler, string to int64 for an ordinal encoding — but the metadata
still described
the input, so the conversion back cast the results to their
pre-transform dtypes.

That round trip landed in 2.54 (ray-project#59810). 2.56 (ray-project#63017) made pandas
batches Arrow-backed,
which is what made those cast-backs fail. So this is a latent bug that
2.56 exposed
rather than one 2.56 introduced: the same call already failed on 2.55
when handed an
Arrow-backed frame directly.

## The fix

Stop round-tripping the batch. Only the columns the preprocessor reads
(`get_input_columns`) cross into Arrow, without the metadata, and only
the ones it writes
(`get_output_columns`) come back. The result is a shallow copy of the
caller's frame with
those columns replaced, so untouched columns, the index, the axis names
and `attrs` never
leave pandas — there is nothing to rebuild.

- A written column that keeps its Arrow type keeps the dtype of the
column it replaces
  (a scaled `Float64` stays `Float64`).
- Otherwise it keeps that column's backing. An Arrow-backed column stays
Arrow-backed
whatever `enable_arrow_backed_pandas_conversion` says — the flag governs
how Ray
converts its own blocks, not the caller's columns — except for the types
Ray never maps
to an Arrow-backed dtype (extension, dictionary, null), which go through
its block
conversion as before. A NumPy-backed column converts plainly, and a
newly created column
  follows the frame.
- That Arrow-to-pandas type mapping moves unchanged from a closure in
`ArrowBlockAccessor.to_pandas` to module level in `arrow_block.py`, so
both paths share
  one rule.
- A preprocessor that declares no columns falls back to sending the
whole frame.

Writing columns back by position needs `_transform_arrow` to return the
rows it was
given, in order. A changed row count now raises a `ValueError`, and the
`_transform_arrow`
docstring states the contract. All three built-in `_transform_arrow`
implementations are
column transforms and satisfy it.

## Behaviour changes

Both come from untouched columns no longer being re-inferred from Arrow:

- An object column of numbers stays `object`; it used to come back
`int64` / `float64`.
- Integer column labels stay integers; they used to be turned into
strings.

And one for implementers: `_transform_arrow` on a pandas batch now
receives only the
declared input columns, and must not change the rows. The previous code
tolerated a
filtering transform by carrying the index through as a column; it now
raises instead.

## Not a fix for

`enable_arrow_backed_pandas_conversion=False` mitigates this only for
Arrow-block sources.
A pandas block built from an already-Arrow-backed frame — what
`pd.read_parquet(..., dtype_backend="pyarrow")` returns — never
undergoes an
Arrow-to-pandas conversion, so the flag does not reach it; this change
fixes that path.

Two related gaps are left for follow-ups rather than widening this PR:

- `Preprocessor.transform(ds)` has the same stale-metadata defect for a
dataset built from
an Arrow-backed pandas frame with the flag set to `False` (it works with
the default).
- `transform_batch(pa.Table)` returns a table that still carries the
caller's pandas
metadata, so calling `.to_pandas()` on the result can fail the same way.

## Not a duplicate

No open PR touches `_transform_batch` or this pandas/Arrow round trip.
The open
preprocessor work (ray-project#66088, ray-project#66091) is about how preprocessors are
*fitted* and does not
change the transform path; ray-project#60533 adds a `drop` option to the one-hot
encoders in
`encoder.py`. The other open Arrow/pandas PRs are elsewhere: ray-project#65539 is
schema
unification for empty datasets, ray-project#63938 preserves `CategoricalDtype` in
`Schema.types`.

No open issue covers it either. ray-project#64765, the umbrella 2.56 `to_pandas`
regression, is
closed, fixed by ray-project#64768 — which added the
`enable_arrow_backed_pandas_conversion`
opt-out and left this round trip untouched.

## Testing

35 `transform_batch` cases added to

`python/ray/data/tests/preprocessors/test_preprocessors_arrow_backed.py`:

- `test_transform_batch_inside_a_pandas_udf` — the three reported
preprocessors through a
  pandas UDF, parametrized over `enable_arrow_backed_pandas_conversion`.
- `test_transform_batch_on_an_arrow_backed_pandas_block` — the shape the
flag does not cover.
- `test_transform_batch_passes_through_an_untouched_list_column` — the
list-column case.
- `test_transform_batch_matches_the_input_backing` /
`..._decides_the_backing_per_column`
— NumPy in gives NumPy out, Arrow in gives Arrow out, and a mixed frame
keeps both.
- `test_transform_batch_keeps_arrow_backing_with_the_flag_off` — the
same holds for all
three preprocessors with `enable_arrow_backed_pandas_conversion=False`.
- `test_transform_batch_keeps_pass_through_extension_dtypes` — nullable
`Int64`, `boolean`
  and `string` columns come back intact, including a value past 2**53.
- `test_transform_batch_leaves_untouched_columns_exactly_as_they_were` —
object columns of
  numbers, a categorical over pandas strings, Python lists.
- `test_transform_batch_preserves_the_index` — named, `MultiIndex` and
tz-aware
  `DatetimeIndex` on both backings, plus the columns axis name.
- `test_transform_batch_keeps_integer_column_labels`,
`..._does_not_modify_the_callers_frame`,
`..._rejects_a_transform_that_changes_the_row_count`,
  `..._on_an_empty_batch`.

The cases assert on values rather than on "did not raise": where the
stale metadata
permitted the cast, the result was silently wrong rather than an error —
an ordinal
encoding coming back as the strings `"0"`, `"1"`, `"2"`.

Against the unmodified source, 21 of the 35 fail:

- 15 are the reported crash on Arrow-backed input.
- 5 are the behaviour changes above: master re-typed untouched object
and categorical
  columns and stringified integer labels.
- 1 is the new contract: master tolerated a filtering
`_transform_arrow`; this raises.

The other 14 pass on master too and are controls — the NumPy-backed
halves, the empty
batch, and the pass-through dtype cases, which guard against a
regression a naive fix
would introduce.

```
$ PYTHONPATH=python/ray/data/tests python -m pytest -q \
    python/ray/data/tests/preprocessors/ --ignore=.../test_torch.py
381 passed, 5 skipped

$ PYTHONPATH=python/ray/data/tests python -m pytest -q python/ray/data/tests/test_arrow_block.py
30 passed
```

The three reported repros were also run end to end through `map_batches`
in Ray workers.
`test_torch.py` is excluded because `torch` is not installed in this
environment; it is
untouched by this change. Pre-commit passes on all three changed files.

Only the declared columns are converted, so wide frames stop paying for
every column:
`StandardScaler(columns=["n"]).transform_batch` on a 1000-column ×
2k-row NumPy frame
goes from ~27 ms to under 1 ms.

AI assistance was used for this change.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Marwan Sarieddine <[email protected]>
Signed-off-by: Aarrya <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Aarrya <[email protected]>
dstrodtman added a commit that referenced this pull request Oct 30, 2026
…cessors (#67603)

## Summary

Adds the missing docstrings on the public
`ray.data.preprocessor.Preprocessor` and `ray.data.preprocessors`
surface: 88 symbols in 13 files. Most are the configuration properties
on each built-in preprocessor, such as `columns`, `output_columns`, and
`bins`. Each property docstring restates the constructor's existing
`Args:` entry. The `get_input_columns` and `get_output_columns`
overrides, `Preprocessor.fit_status`, `Chain.fit_status`,
`Preprocessor.has_stats`, and `OneHotEncoder.safe_get` now get
docstrings with `Returns:` sections, written from what the code returns.

## Before

These properties and methods had no docstring, so the API reference
showed only their names and signatures.

## After

They have docstrings. Overrides that now carry their own docstring, such
as `LabelEncoder.get_input_columns`, appear in their class's method
table, because the `class.rst` autosummary template lists only methods
whose own `__doc__` is set.

Behavior is unchanged. The diff touches only docstrings, which the guard
below confirms.

## Subsystems

API (preprocessors). Docstrings only.

## For reviewers

The descriptions of what a method returns, such as `fit_status`,
`has_stats`, `safe_get`, and the base `get_input_columns` and
`get_output_columns`, are the parts worth a technical read. The property
docstrings paraphrase each class's `Args:` section.

While writing these, I found that
`TorchVisionPreprocessor.preferred_batch_format` is missing the
`@classmethod` that the base method and the other overrides carry.
That's a code change, so it's in #67602 instead of here, and the two PRs
touch adjacent lines.

## Duplicate check

No open PR documents these symbols. I searched open PRs for
`preprocessor docstring` and `preprocessors`. #60533 changes
`OneHotEncoder` and `MultiHotEncoder` code in `encoder.py` but doesn't
touch these docstrings.

## Testing

- `python ci/ray_ci/doc/check_docstring_only.py --base "$(git merge-base
upstream/master HEAD)"`: `docstring-only guard: 13 file(s), docstrings
only.`
- The full pre-commit suite on the changed files, including ruff, black,
pydoclint, and the docstyle hook: passed.
- The commit carries an `@rtd-build` line, so the Read the Docs preview
renders the new docstrings.

AI assistance (Claude Code) was used to prepare this PR.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Douglas Strodtman <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community data Ray Data-related issues go add ONLY when ready to merge, run all tests unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants