Skip to content

[Data] Fix index alignment and empty-batch handling in FeatureHasher, Concatenator, and PowerTransformer - #67483

Merged
richardliaw merged 4 commits into
ray-project:masterfrom
deep1blue:fix/preprocessors-index-and-empty-batch
Nov 24, 2026
Merged

richardliaw merged 4 commits into
ray-project:masterfrom
deep1blue:fix/preprocessors-index-and-empty-batch

Conversation

@deep1blue

@deep1blue deep1blue commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Why are these changes needed?

This PR fixes silent NaN corruption on non-default pd.DataFrame indices in Concatenator and FeatureHasher, and exceptions on zero-row batches in FeatureHasher and PowerTransformer:

  1. Preserve df.index in Concatenator._transform_pandas and FeatureHasher._transform_pandas (TestConcatenator.test_non_default_index, test_feature_hasher):
    Both preprocessors previously assigned df.loc[:, output_col] = pd.Series(list(concatenated)) without index=df.index. When transform_batch is called on a sliced, filtered, or custom-indexed pd.DataFrame whose index is not RangeIndex(0, len(df)) (e.g., index=[10, 20]), pandas aligns the newly created Series index (0..n-1) against df.index and silently replaces non-overlapping index positions with NaN. Passing index=df.index preserves row alignment.
  2. Handle zero-row batches and hoist column-name hashing in FeatureHasher._transform_pandas (test_feature_hasher):
    • On an empty pd.DataFrame (len(df) == 0), df.loc[:, self._columns].apply(row_feature_hasher, axis=1, result_type="expand") returns a 0-row DataFrame with self._columns rather than hash_0 .. hash_{num_features - 1}, causing feature_columns[hash_columns] to raise KeyError. Returning an empty object-dtype Series indexed by df.index when df.empty avoids the crash.
    • Precomputes simple_hash(column, self._num_features) once per column per batch rather than recomputing the SHA-256 column-name hash inside row_feature_hasher on every row.
  3. Return pd.Series(result, index=s.index) in PowerTransformer._transform_pandas (yeo-johnson, test_power_transformer_empty_batch):
    Unlike the box-cox branch (which returns a pd.Series), the yeo-johnson branch returned a raw np.ndarray. On an empty DataFrame (len(df) == 0), pandas.DataFrame.transform treats a non-Series return value in apply_empty_result as a scalar reduction and raises ValueError: Transform function failed. Returning pd.Series(result, index=s.index) makes yeo-johnson consistent with box-cox on empty batches.

Related work & acknowledgements

Related issue number

N/A

Checks

… Concatenator, and PowerTransformer

Signed-off-by: Parth Vadera <[email protected]>
Co-authored-by: Copilot <[email protected]>
Signed-off-by: Parth Vadera <[email protected]>
@deep1blue
deep1blue requested a review from a team as a code owner October 27, 2026 16:30

@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 updates several preprocessors (Concatenator, FeatureHasher, and PowerTransformer) to correctly handle empty batches and preserve non-default DataFrame indices during transformations, along with adding corresponding unit tests. The review feedback highlights a potential ValueError when using pd.Series(..., index=df.index) for column assignment if the input DataFrame contains duplicate index values. It is recommended to convert the Series to a NumPy array using .to_numpy() to avoid index alignment issues while maintaining robustness.

Comment on lines +181 to +183
df.loc[:, self._output_column_name] = pd.Series(
list(concatenated), index=df.index
)

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.

high

Using pd.Series(..., index=df.index) for column assignment will raise a ValueError: cannot reindex on an axis with duplicate labels if the input DataFrame contains duplicate index values. Converting the Series to a raw NumPy array using .to_numpy() avoids index alignment entirely, making the assignment robust to duplicate indices while still preserving the DataFrame's original index.

Suggested change
df.loc[:, self._output_column_name] = pd.Series(
list(concatenated), index=df.index
)
df[self._output_column_name] = pd.Series(
list(concatenated)
).to_numpy()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Because pd.Series(list(concatenated), index=df.index) passes the exact df.index instance (val.index.equals(df.index) is True), Pandas skips reindex() during df.loc[:, col] = ... even when df.index contains duplicate labels, while keeping Series-based column assignment across Pandas versions.

Comment thread python/ray/data/preprocessors/hasher.py Outdated
Comment on lines +150 to +152
df.loc[:, self._output_column] = pd.Series(
list(concatenated), index=df.index
)

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.

high

Similar to the change in Concatenator, using pd.Series(..., index=df.index) here will cause a ValueError: cannot reindex on an axis with duplicate labels if the input DataFrame contains duplicate indices. Converting the Series to a NumPy array via .to_numpy() avoids index alignment entirely, making the assignment robust to duplicate indices while still preserving the DataFrame's original index.

Suggested change
df.loc[:, self._output_column] = pd.Series(
list(concatenated), index=df.index
)
df[self._output_column] = pd.Series(
list(concatenated)
).to_numpy()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Because pd.Series(list(concatenated), index=df.index) passes the exact df.index instance (val.index.equals(df.index) is True), Pandas skips reindex() during df.loc[:, col] = ... even when df.index contains duplicate labels, while keeping Series-based column assignment across Pandas versions.

@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Oct 27, 2026
Co-authored-by: Copilot <[email protected]>
Signed-off-by: Parth Vadera <[email protected]>
@github-actions

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 Nov 14, 2026
@deep1blue

Copy link
Copy Markdown
Contributor Author

Keeping this PR open — the branch remains cleanly mergeable with master (mergeable=True, DCO success) and is ready for maintainer review. Please let me know if any updates or additional tests would be helpful!

@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 Nov 14, 2026
@abhishekverma-ray abhishekverma-ray added the go add ONLY when ready to merge, run all tests label Nov 18, 2026

@abhishekverma-ray abhishekverma-ray 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.

The code changes look right. Some test halves pass on master:

  • In test_power_transformer_empty_batch_and_index, only yeo-johnson on an empty batch fails on master. The index half and the box-cox cases pass, and power doesn't affect the changed line. One yeo-johnson empty-batch case would cover it.
  • In TestConcatenator.test_non_default_index_and_empty_batch, the empty-batch half passes on master for both flatten values. Keep the index assert.

The PowerTransformer change fixes empty yeo-johnson batches rather than index alignment, so the description could be updated. test_feature_hasher_non_default_index_and_empty_batch is good, and could be folded into test_feature_hasher.

@deep1blue

Copy link
Copy Markdown
Contributor Author

Thanks for the review @abhishekverma-ray! Updated in 03574d9:

  • Trimmed test_power_transformer_empty_batch down to a single yeo-johnson empty-batch case.
  • Dropped the empty-batch half of the Concatenator test (TestConcatenator.test_non_default_index).
  • Folded the non-default index and empty-batch checks into test_feature_hasher and removed the separate test function.
  • Updated the PR description to reflect the final changes and test cases.

Verified locally with pytest python/ray/data/tests/preprocessors/test_concatenator.py python/ray/data/tests/preprocessors/test_hasher.py python/ray/data/tests/preprocessors/test_transformer.py -k "test_non_default_index or test_feature_hasher or test_power_transformer_empty_batch" (5 passed).

@richardliaw
richardliaw merged commit 9adfa1a into ray-project:master Nov 24, 2026
6 checks passed
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