Repository navigation
[Data] Count nulls in pandas value_counts to match Arrow - #68264
Conversation
There was a problem hiding this comment.
Code Review
This pull request ensures that value_counts behavior is consistent across both Arrow and Pandas backends in Ray Data by normalizing all null-ish index entries to a canonical None in PandasBlockColumnAccessor.value_counts and adding property-based tests to verify backend agreement. Feedback is provided to address a potential bug where multiple different null representations (e.g., None and NaN) could lead to duplicate None keys in the returned value_counts dictionary, and to simplify the _is_scalar_null helper function using pandas.api.types.is_scalar.
| return { | ||
| "values": value_counts.index.tolist(), | ||
| "values": [ | ||
| None if _is_scalar_null(value) else value | ||
| for value in value_counts.index.tolist() | ||
| ], | ||
| "counts": value_counts.values.tolist(), | ||
| } |
There was a problem hiding this comment.
If a pandas Series contains multiple different null representations (e.g., both None and NaN in an object dtype column), self._column.value_counts(dropna=False) will return separate entries for each null representation. Normalizing them to None without merging them will result in duplicate None keys in the returned dictionary's values list, violating the contract of value_counts returning unique values and causing incorrect aggregation results in ValueCounter when there is only a single block. We should merge duplicate normalized keys and sum their counts.
| return { | |
| "values": value_counts.index.tolist(), | |
| "values": [ | |
| None if _is_scalar_null(value) else value | |
| for value in value_counts.index.tolist() | |
| ], | |
| "counts": value_counts.values.tolist(), | |
| } | |
| normalized_counts = {} | |
| for value, count in zip(value_counts.index.tolist(), value_counts.values.tolist()): | |
| norm_value = None if _is_scalar_null(value) else value | |
| normalized_counts[norm_value] = normalized_counts.get(norm_value, 0) + count | |
| return { | |
| "values": list(normalized_counts.keys()), | |
| "counts": list(normalized_counts.values()), | |
| } |
There was a problem hiding this comment.
Right diagnosis, but I fixed it differently in cd53c60. The suggested dict depends on the removed helper and would merge 0.0/-0.0, which Arrow keeps distinct.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 708a30f. Configure here.
Addresses review feedback on #68264: the previous per-value null check mapped both NaN and pd.NA to None, so an Arrow-backed float column holding both produced two `None` entries in `values`. `ValueCounter.combine` keys a dict on the value, so one of them was silently dropped, and it diverged from Arrow, which counts NaN as a value of its own. Whether NaN is a value or a missing marker is a property of the dtype, not of the scalar, so use pandas' own dtype-aware `Index.isna()` mask instead: NaN stays a distinct value for Arrow-backed columns (matching Arrow's `value_counts`), and is treated as missing for numpy and nullable columns, where converting the block to Arrow turns it into null anyway. Extends the property test to float columns containing NaN, which is the case the string-only strategy could not reach. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Goutam <[email protected]>
There was a problem hiding this comment.
Object-dtype columns can still produce duplicate None keys, reached when doing aggregations. Should we fix?
In an object column, pandas counts None, NaN and pd.NA as separate entries with dropna=False. Index.isna() flags all of them, so each one becomes its own None and nothing merges them afterwards. combine doesn't merge them either, because the duplicates arrive inside a single accumulator.
import numpy as np, pandas as pd, ray
from ray.data.aggregate import ValueCounter
from ray.data.context import DataContext, ShuffleStrategy
DataContext.get_current().shuffle_strategy = ShuffleStrategy.HASH_SHUFFLE # or SORT_SHUFFLE_PULL_BASED
df = pd.DataFrame({"x": pd.Series(["a", None, np.nan, "a"], dtype=object)})
print(ray.data.from_pandas(df).aggregate(ValueCounter(on="x")))| Column (object dtype) | This PR (hash / sort shuffle) | Master |
|---|---|---|
["a", None, nan, "a"] |
['a', None, None], [2, 1, 1] |
['a'], [2] |
["a", None, nan, pd.NA] |
['a', None, None, None], [1, 1, 1, 1] |
['a'], [1] |
[1.0, None, nan] |
[1.0, None, None], [1, 1, 1] |
[1.0], [1] |
The last row also disagrees with the default shuffle_v2, which returns [1.0, None, nan] because Ray's Arrow conversion keeps that NaN as a value.
| # "numpy" -> plain numpy dtype with NaN for missing (pandas-returning UDFs) | ||
| PANDAS_DTYPES = ["pyarrow", "nullable", "numpy"] | ||
|
|
||
| string_values = st.lists( |
There was a problem hiding this comment.
Is this unused? We should replace the @given decorator param with string_values
There was a problem hiding this comment.
Yes, it was unused. The strings test now uses string_values (cd53c60).
|
|
||
| settings.register_profile( | ||
| "ray_data_ci", | ||
| max_examples=200, |
There was a problem hiding this comment.
Qq: How do we set this?
Is there an idiomatic way to decide a good sample space for hypothesis to use, depending on the factors like inputs, conditional branches/complex logic, cost of running the function on CI, etc. ?
It's fine if we use a reasonable default like 200 for functions like value_counts but if we want to expand PB testing to other parts of the Ray Data code we should document this
There was a problem hiding this comment.
There's no formula. 100 is Hypothesis' default, and we raise it while the tests stay cheap. The tradeoff is now documented in tests/conftest.py, along with a ray_data_thorough profile (5000 examples) for searching harder locally: HYPOTHESIS_PROFILE=ray_data_thorough pytest ....
| settings.register_profile( | ||
| "ray_data_ci", | ||
| max_examples=200, | ||
| derandomize=True, |
There was a problem hiding this comment.
Nit: Could we move the profile to conftest.py, if it is going to be shared across different PB test files?
There was a problem hiding this comment.
Done in cd53c60. I put it in tests/conftest.py, not tests/unit/conftest.py, because the unit tests' Bazel deps only pull in the former, so a profile in the latter would silently not load in CI. load_profile is process-global, so the sibling test_transform_pyarrow_properties.py now uses the shared one too.
| "values": [ | ||
| None if is_missing else value | ||
| for value, is_missing in zip(index.tolist(), missing.tolist()) | ||
| ], |
There was a problem hiding this comment.
nit: Can we avoid this Python loop here, given that this code can be called once per block aggregation?
| "values": [ | |
| None if is_missing else value | |
| for value, is_missing in zip(index.tolist(), missing.tolist()) | |
| ], | |
| "values": index.astype(object).where(~missing, None).tolist(), |
This would keep it vectorized, and also preserve the same type of the arbitrary values as it is on master, as well as preserving the same behaviour / output types as this PR
There was a problem hiding this comment.
Done in cd53c60. The split is now boolean-mask indexing. One small loop remains for object dtype only, and it visits only the missing entries of the deduplicated index (at most a few).
ayushk7102
left a comment
There was a problem hiding this comment.
Some nits, and one blocker (added repro).
Addresses review feedback on #68264: the previous per-value null check mapped both NaN and pd.NA to None, so an Arrow-backed float column holding both produced two `None` entries in `values`. `ValueCounter.combine` keys a dict on the value, so one of them was silently dropped, and it diverged from Arrow, which counts NaN as a value of its own. Whether NaN is a value or a missing marker is a property of the dtype, not of the scalar, so use pandas' own dtype-aware `Index.isna()` mask instead: NaN stays a distinct value for Arrow-backed columns (matching Arrow's `value_counts`), and is treated as missing for numpy and nullable columns, where converting the block to Arrow turns it into null anyway. Extends the property test to float columns containing NaN, which is the case the string-only strategy could not reach. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Goutam <[email protected]>
943a880 to
9d6a141
Compare
|
@ayushk7102 Good catch, fixed in cd53c60. The object-dtype case was a bit broader than duplicate |
`pd.Series.value_counts()` drops nulls by default while Arrow's `value_counts` counts them as values of their own, so the same logical data produced a different ValueCounter result depending on whether the block was Arrow- or pandas-backed. Block type is not something a user controls per block, so the aggregation must not depend on it. Pass `dropna=False` and normalize pandas' missing sentinels to a single canonical `None`, matching the Arrow semantics that #68202 specifies for this aggregation. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Goutam <[email protected]>
Addresses review feedback on #68264: the previous per-value null check mapped both NaN and pd.NA to None, so an Arrow-backed float column holding both produced two `None` entries in `values`. `ValueCounter.combine` keys a dict on the value, so one of them was silently dropped, and it diverged from Arrow, which counts NaN as a value of its own. Whether NaN is a value or a missing marker is a property of the dtype, not of the scalar, so use pandas' own dtype-aware `Index.isna()` mask instead: NaN stays a distinct value for Arrow-backed columns (matching Arrow's `value_counts`), and is treated as missing for numpy and nullable columns, where converting the block to Arrow turns it into null anyway. Extends the property test to float columns containing NaN, which is the case the string-only strategy could not reach. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Goutam <[email protected]>
…ue_counts An object column reports None, NaN and pd.NA as separate value_counts entries, and ValueCounter.combine never merges duplicate keys within one accumulator, so a block could emit several None keys. Fold them into one. Mirror to_arrow: a float NaN in an object column converts to a double NaN (a value), unless the column has no non-missing entry, in which case it becomes Arrow null. Also vectorize the missing-value split, move the shared Hypothesis profile into tests/conftest.py (load_profile is process-global), and use the previously unused string_values strategy. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Goutam <[email protected]>
cd53c60 to
bfbc776
Compare

Summary
ValueCounterreturns different results for the same data depending on whether a block is Arrow- or pandas-backed.pd.Series.value_counts()drops nulls, while Arrow'svalue_countscounts them:Users don't choose a block's format; it depends on upstream operators and
batch_format. So today, adding amap_batches(..., batch_format="pandas")upstream silently changes the counts. This PR makes the pandas path match Arrow, which is the behavior #68202 specifies invalue_counter_spec().Changes
PandasBlockColumnAccessor.value_countsnow counts nulls. It also normalizespd.NA,NaNandNoneto a singleNonekey. Without that,ValueCounter.combinewouldn't merge them with Arrow'sNoneacross blocks, andNaNwouldn't reliably merge with itself._is_scalar_null, becauseutil.is_nullmissespd.NA/pd.NaT. Wideningis_nullwould also change every aggregation's null-safety wrappers, so that's left for a separate change. (aggregate.py's null-stripping loop has the same gap today.)aggregate.pythat said pandas drops nulls is updated. The accounting it describes stays correct.Tests
Adds
test_block_column_accessor_properties.py, which useshypothesisfrom #68259. Its properties:int64[pyarrow], nullableInt64/string, numpy). This fails on the parent commit and passes here.sum/min/max/mean/count.pre-commit runpasses on all changed files.Not a duplicate
No open PR changes
PandasBlockColumnAccessor.value_counts. #68202 and #67664 touchValueCounteron the Arrow/vectorized path, not the pandas accessor. This change is complementary.Subsystems: Block / data format; Shuffle / aggregation
AI assistance was used for this change. Property-based testing across the two
BlockColumnAccessorimplementations found the divergence.