Repository navigation
[Data] Fix index alignment and empty-batch handling in FeatureHasher, Concatenator, and PowerTransformer - #67483
Conversation
… Concatenator, and PowerTransformer Signed-off-by: Parth Vadera <[email protected]> Co-authored-by: Copilot <[email protected]> Signed-off-by: Parth Vadera <[email protected]>
There was a problem hiding this comment.
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.
| df.loc[:, self._output_column_name] = pd.Series( | ||
| list(concatenated), index=df.index | ||
| ) |
There was a problem hiding this comment.
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.
| df.loc[:, self._output_column_name] = pd.Series( | |
| list(concatenated), index=df.index | |
| ) | |
| df[self._output_column_name] = pd.Series( | |
| list(concatenated) | |
| ).to_numpy() |
There was a problem hiding this comment.
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.
| df.loc[:, self._output_column] = pd.Series( | ||
| list(concatenated), index=df.index | ||
| ) |
There was a problem hiding this comment.
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.
| df.loc[:, self._output_column] = pd.Series( | |
| list(concatenated), index=df.index | |
| ) | |
| df[self._output_column] = pd.Series( | |
| list(concatenated) | |
| ).to_numpy() |
There was a problem hiding this comment.
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.
Co-authored-by: Copilot <[email protected]> Signed-off-by: Parth Vadera <[email protected]>
|
This pull request has been automatically marked as stale because it has not had 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. |
|
Keeping this PR open — the branch remains cleanly mergeable with |
abhishekverma-ray
left a comment
There was a problem hiding this comment.
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, andpowerdoesn'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 bothflattenvalues. 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.
Co-authored-by: Copilot <[email protected]> Signed-off-by: Parth Vadera <[email protected]>
…ty_batch Co-authored-by: Copilot <[email protected]> Signed-off-by: Parth Vadera <[email protected]>
|
Thanks for the review @abhishekverma-ray! Updated in 03574d9:
Verified locally with |
Why are these changes needed?
This PR fixes silent
NaNcorruption on non-defaultpd.DataFrameindices inConcatenatorandFeatureHasher, and exceptions on zero-row batches inFeatureHasherandPowerTransformer:df.indexinConcatenator._transform_pandasandFeatureHasher._transform_pandas(TestConcatenator.test_non_default_index,test_feature_hasher):Both preprocessors previously assigned
df.loc[:, output_col] = pd.Series(list(concatenated))withoutindex=df.index. Whentransform_batchis called on a sliced, filtered, or custom-indexedpd.DataFramewhose index is notRangeIndex(0, len(df))(e.g.,index=[10, 20]), pandas aligns the newly createdSeriesindex (0..n-1) againstdf.indexand silently replaces non-overlapping index positions withNaN. Passingindex=df.indexpreserves row alignment.FeatureHasher._transform_pandas(test_feature_hasher):pd.DataFrame(len(df) == 0),df.loc[:, self._columns].apply(row_feature_hasher, axis=1, result_type="expand")returns a 0-row DataFrame withself._columnsrather thanhash_0 .. hash_{num_features - 1}, causingfeature_columns[hash_columns]to raiseKeyError. Returning an emptyobject-dtypeSeriesindexed bydf.indexwhendf.emptyavoids the crash.simple_hash(column, self._num_features)once per column per batch rather than recomputing the SHA-256 column-name hash insiderow_feature_hasheron every row.pd.Series(result, index=s.index)inPowerTransformer._transform_pandas(yeo-johnson,test_power_transformer_empty_batch):Unlike the
box-coxbranch (which returns apd.Series), theyeo-johnsonbranch returned a rawnp.ndarray. On an empty DataFrame (len(df) == 0),pandas.DataFrame.transformtreats a non-Seriesreturn value inapply_empty_resultas a scalar reduction and raisesValueError: Transform function failed. Returningpd.Series(result, index=s.index)makesyeo-johnsonconsistent withbox-coxon empty batches.Related work & acknowledgements
FeatureHasherappend-mode support in [data/preprocessors] feat: allow hasher to run on append mode #50632 by @martinbomio.Related issue number
N/A
Checks
git commit -s) in this PR.scripts/format.shto lint the changes in this PR.doc/source/tune/api/under the corresponding.rstfile.python/ray/data/tests/preprocessors/test_concatenator.py,python/ray/data/tests/preprocessors/test_hasher.py,python/ray/data/tests/preprocessors/test_transformer.py)