Skip to content

[Data] Count nulls in pandas value_counts to match Arrow - #68264

Merged
goutamvenkat-anyscale merged 3 commits into
masterfrom
goutam/data-fix-value-counts-backend-parity
Nov 25, 2026
Merged

goutamvenkat-anyscale merged 3 commits into
masterfrom
goutam/data-fix-value-counts-backend-parity

Conversation

@goutamvenkat-anyscale

@goutamvenkat-anyscale goutamvenkat-anyscale commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #68259. Review that one first.

Summary

ValueCounter returns different results for the same data depending on whether a block is Arrow- or pandas-backed. pd.Series.value_counts() drops nulls, while Arrow's value_counts counts them:

vals = ["a", None, "b", "a"]
arrow  -> {'values': ['a', None, 'b'], 'counts': [2, 1, 1]}
pandas -> {'values': ['a', 'b'],       'counts': [2, 1]}

Users don't choose a block's format; it depends on upstream operators and batch_format. So today, adding a map_batches(..., batch_format="pandas") upstream silently changes the counts. This PR makes the pandas path match Arrow, which is the behavior #68202 specifies in value_counter_spec().

Changes

  • PandasBlockColumnAccessor.value_counts now counts nulls. It also normalizes pd.NA, NaN and None to a single None key. Without that, ValueCounter.combine wouldn't merge them with Arrow's None across blocks, and NaN wouldn't reliably merge with itself.
  • The null check is a new local _is_scalar_null, because util.is_null misses pd.NA/pd.NaT. Widening is_null would 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.)
  • A stale comment in aggregate.py that said pandas drops nulls is updated. The accounting it describes stays correct.

Tests

Adds test_block_column_accessor_properties.py, which uses hypothesis from #68259. Its properties:

  • Arrow and pandas agree, across the pandas dtypes Ray Data produces (int64[pyarrow], nullable Int64/string, numpy). This fails on the parent commit and passes here.
  • Counts sum to the row count.
  • A regression guard for sum/min/max/mean/count.
pytest python/ray/data/tests/unit/        -> 2997 passed, 208 skipped
pytest python/ray/data/tests/unit/test_block_column_accessor_properties.py \
       python/ray/data/tests/unit/test_transform_pyarrow_properties.py  -> 7 passed

pre-commit run passes on all changed files.

Not a duplicate

No open PR changes PandasBlockColumnAccessor.value_counts. #68202 and #67664 touch ValueCounter on 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 BlockColumnAccessor implementations found the divergence.

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

Comment on lines 395 to 401
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(),
}

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

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.

Suggested change
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()),
}

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.

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.

@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 using default effort and found 1 potential issue.

Fix All in Cursor

❌ 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.

@goutamvenkat-anyscale goutamvenkat-anyscale added data Ray Data-related issues go add ONLY when ready to merge, run all tests labels Nov 17, 2026
goutamvenkat-anyscale added a commit that referenced this pull request Nov 17, 2026
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]>

@ayushk7102 ayushk7102 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.

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(

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 this unused? We should replace the @given decorator param with string_values

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.

Yes, it was unused. The strings test now uses string_values (cd53c60).


settings.register_profile(
"ray_data_ci",
max_examples=200,

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.

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

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.

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,

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.

Nit: Could we move the profile to conftest.py, if it is going to be shared across different PB test files?

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.

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.

Comment on lines +386 to +389
"values": [
None if is_missing else value
for value, is_missing in zip(index.tolist(), missing.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.

nit: Can we avoid this Python loop here, given that this code can be called once per block aggregation?

Suggested change
"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

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.

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 ayushk7102 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.

Some nits, and one blocker (added repro).

Base automatically changed from goutam/data-fix-unify-schemas-null-list-order to master November 19, 2026 01:23
@goutamvenkat-anyscale
goutamvenkat-anyscale requested a review from a team as a code owner November 19, 2026 01:23
goutamvenkat-anyscale added a commit that referenced this pull request Nov 19, 2026
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]>
@goutamvenkat-anyscale
goutamvenkat-anyscale force-pushed the goutam/data-fix-value-counts-backend-parity branch from 943a880 to 9d6a141 Compare November 19, 2026 01:23
@goutamvenkat-anyscale

Copy link
Copy Markdown
Contributor Author

@ayushk7102 Good catch, fixed in cd53c60. The object-dtype case was a bit broader than duplicate Nones: a float NaN there was also reported as None, while to_arrow converts it to a double NaN value. Missing entries now collapse to one None and follow to_arrow: NaN is a value unless the column has no non-missing entry, in which case it becomes Arrow null. Your three repro rows each give a single None through ValueCounter. I added two property tests, and both fail on the previous HEAD.

`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]>
@goutamvenkat-anyscale
goutamvenkat-anyscale force-pushed the goutam/data-fix-value-counts-backend-parity branch from cd53c60 to bfbc776 Compare November 25, 2026 17:36
@goutamvenkat-anyscale
goutamvenkat-anyscale merged commit 499555f into master Nov 25, 2026
5 checks passed
@goutamvenkat-anyscale
goutamvenkat-anyscale deleted the goutam/data-fix-value-counts-backend-parity branch November 25, 2026 23:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

data Ray Data-related issues go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants