Repository navigation
Conversation
`Dataset.to_pandas()` builds the result by iterating `iter_batches`, which yields no batches for an empty dataset. The `PandasBlockBuilder` then produces a DataFrame with zero columns, so e.g. `from_arrow_refs([empty_table_with_columns]).to_pandas()` returned a frame with no columns even though the dataset's schema is known (issue ray-project#59946). When the built DataFrame has no columns, reconstruct the columns (and dtypes, when the underlying schema is an Arrow schema) from the dataset schema. Closes ray-project#59946 Signed-off-by: lonexreb <[email protected]>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
There was a problem hiding this comment.
Code Review
This pull request addresses an issue where calling to_pandas() on an empty dataset returned a DataFrame with no columns. The fix restores the columns and dtypes from the dataset schema when the resulting DataFrame is empty. The review feedback suggests extending this dtype preservation to PandasBlockSchema and expanding the test coverage to verify dtype preservation for both Arrow-backed and Pandas-backed empty datasets.
| base_schema = getattr(schema, "base_schema", None) | ||
| if isinstance(base_schema, pa.Schema): | ||
| df = base_schema.empty_table().to_pandas() | ||
| else: | ||
| import pandas | ||
|
|
||
| df = pandas.DataFrame(columns=list(schema.names)) |
There was a problem hiding this comment.
When the underlying schema is a PandasBlockSchema, we can also preserve the correct column dtypes instead of falling back to default/object dtypes. We can check if base_schema is an instance of PandasBlockSchema and reconstruct the empty DataFrame with the corresponding pandas dtypes.
base_schema = getattr(schema, "base_schema", None)
if isinstance(base_schema, pa.Schema):
df = base_schema.empty_table().to_pandas()
else:
from ray.data._internal.pandas_block import PandasBlockSchema
if isinstance(base_schema, PandasBlockSchema):
import pandas
from ray.data.extensions import TensorDtype
df = pandas.DataFrame(
{
col: pandas.Series(
dtype=(
dtype
if not isinstance(dtype, TensorDtype)
else np.object_
)
)
for col, dtype in zip(base_schema.names, base_schema.types)
}
)
else:
import pandas
df = pandas.DataFrame(columns=list(schema.names))| ds = ray.data.from_arrow_refs( | ||
| [ray.put(pa.table([pa.array([], pa.int32())], ["apples"]))] | ||
| ) | ||
| df = ds.to_pandas() | ||
| assert list(df.columns) == ["apples"] | ||
| assert len(df) == 0 | ||
|
|
||
| # Multiple columns are preserved too. | ||
| ds2 = ray.data.from_arrow_refs( | ||
| [ | ||
| ray.put( | ||
| pa.table( | ||
| [pa.array([], pa.int32()), pa.array([], pa.string())], ["a", "b"] | ||
| ) | ||
| ) | ||
| ] | ||
| ) | ||
| assert list(ds2.to_pandas().columns) == ["a", "b"] |
There was a problem hiding this comment.
Let's expand the test coverage to verify that dtypes are correctly preserved for both Arrow-backed and Pandas-backed empty datasets.
ds = ray.data.from_arrow_refs(
[ray.put(pa.table([pa.array([], pa.int32())], ["apples"]))]
)
df = ds.to_pandas()
assert list(df.columns) == ["apples"]
assert df["apples"].dtype == np.int32
assert len(df) == 0
# Multiple columns are preserved too.
ds2 = ray.data.from_arrow_refs(
[
ray.put(
pa.table(
[pa.array([], pa.int32()), pa.array([], pa.string())], ["a", "b"]
)
)
]
)
df2 = ds2.to_pandas()
assert list(df2.columns) == ["a", "b"]
assert df2["a"].dtype == np.int32
assert df2["b"].dtype == object
# Pandas-backed empty dataset dtypes are preserved too.
empty_df = pd.DataFrame({"a": pd.Series(dtype="int32"), "b": pd.Series(dtype="string")})
ds3 = ray.data.from_pandas([empty_df])
df3 = ds3.to_pandas()
assert list(df3.columns) == ["a", "b"]
assert df3["a"].dtype == np.int32
assert df3["b"].dtype == "string"
assert len(df3) == 0Address review feedback: when the empty dataset's schema is a PandasBlockSchema, build the empty DataFrame with per-column dtypes from schema.types instead of falling back to object dtype. Expand the test to assert dtypes for both Arrow-backed and Pandas-backed empty datasets. Signed-off-by: lonexreb <[email protected]>
|
Good suggestions, thanks — done. The pandas-backed fallback now preserves per-column dtypes via |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 15a3f8f. Configure here.
… parity Address review feedback (cursor): reconstruct the empty Arrow-backed result via BlockAccessor.for_block(...).to_pandas() instead of pyarrow's empty_table().to_pandas() so empty and non-empty results agree on column dtypes (e.g. both use the Arrow-backed int32[pyarrow] dtype). Update the test to assert the empty dtype matches a non-empty dataset of the same schema. Signed-off-by: lonexreb <[email protected]>
|
Good catch — you're right that |
|
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. |
|
This pull request has been automatically closed because there has been no more activity in the 14 days Please feel free to reopen or open a new pull request if you'd still like this to be addressed. Again, you can always ask for help on our discussion forum or Ray's public slack channel. Thanks again for your contribution! |
…o_pandas() (#65539) ## Why are these changes needed? `Dataset.to_pandas()` (and schema propagation generally) drops columns for an empty dataset: ```python import pyarrow as pa, ray empty_ref = ray.put(pa.table([pa.array([], pa.int32())], ["apples"])) rd = ray.data.from_arrow_refs([empty_ref]) assert list(rd.to_pandas().columns) == ["apples"] # fails on master: columns == [] ``` Two layers cause this: 1. **Metadata layer**: `unify_block_metadata_schema()` / `unify_ref_bundles_schema()` skip blocks with `num_rows == 0`, so a dataset made *only* of empty blocks reports no schema — even though an empty Arrow table carries a perfectly valid one (as noted by @mango766 on the issue). This PR makes empty-block schemas a fallback when no non-empty block provides a schema; non-empty blocks still take precedence. 2. **Consumption layer**: `to_pandas()` builds its result from `iter_batches()`, which yields no batches for an empty dataset, so `PandasBlockBuilder.build()` produced a DataFrame with zero columns. This PR reconstructs columns and dtypes from the dataset schema, routing Arrow-backed schemas through the same `BlockAccessor.to_pandas()` path used for non-empty blocks so empty and non-empty results agree on dtypes. This supersedes #64721 (same fix for layer 2, closed by the stale bot after both bot-review comments had been addressed; GitHub would not allow reopening it). This PR carries those commits, rebased on current master, plus the new metadata-layer fix. ## Related issue number Fixes #59946 ## Checks - [x] I've signed off every commit (DCO). - [x] I've run pre-commit formatting (`black==22.10.0` per repo pin) on changed files. - [x] Testing strategy: - Added `test_to_pandas_empty_dataset_preserves_columns` (Arrow-backed and pandas-backed empty datasets, dtype parity with non-empty datasets). - Added `test_unify_block_metadata_schema_all_empty_blocks` (fallback + precedence). - Ran locally against master with the Ray nightly wheel + `setup-dev.py` symlinks: - `pytest python/ray/data/tests/test_util.py` → 39 passed - `pytest python/ray/data/tests/test_arrow_block.py -k to_pandas` → 13 passed - Issue's exact repro passes. ### Notes for reviewers / AI-assistance disclosure - This PR was prepared with AI assistance; I have reviewed every changed line and run the tests above locally. - Duplicate-work check: no other open PR references #59946; the only prior PR was my own #64721, which this supersedes. --------- Signed-off-by: lonexreb <[email protected]> Signed-off-by: iamjustinhsu <[email protected]> Co-authored-by: iamjustinhsu <[email protected]>
…o_pandas() (ray-project#65539) ## Why are these changes needed? `Dataset.to_pandas()` (and schema propagation generally) drops columns for an empty dataset: ```python import pyarrow as pa, ray empty_ref = ray.put(pa.table([pa.array([], pa.int32())], ["apples"])) rd = ray.data.from_arrow_refs([empty_ref]) assert list(rd.to_pandas().columns) == ["apples"] # fails on master: columns == [] ``` Two layers cause this: 1. **Metadata layer**: `unify_block_metadata_schema()` / `unify_ref_bundles_schema()` skip blocks with `num_rows == 0`, so a dataset made *only* of empty blocks reports no schema — even though an empty Arrow table carries a perfectly valid one (as noted by @mango766 on the issue). This PR makes empty-block schemas a fallback when no non-empty block provides a schema; non-empty blocks still take precedence. 2. **Consumption layer**: `to_pandas()` builds its result from `iter_batches()`, which yields no batches for an empty dataset, so `PandasBlockBuilder.build()` produced a DataFrame with zero columns. This PR reconstructs columns and dtypes from the dataset schema, routing Arrow-backed schemas through the same `BlockAccessor.to_pandas()` path used for non-empty blocks so empty and non-empty results agree on dtypes. This supersedes ray-project#64721 (same fix for layer 2, closed by the stale bot after both bot-review comments had been addressed; GitHub would not allow reopening it). This PR carries those commits, rebased on current master, plus the new metadata-layer fix. ## Related issue number Fixes ray-project#59946 ## Checks - [x] I've signed off every commit (DCO). - [x] I've run pre-commit formatting (`black==22.10.0` per repo pin) on changed files. - [x] Testing strategy: - Added `test_to_pandas_empty_dataset_preserves_columns` (Arrow-backed and pandas-backed empty datasets, dtype parity with non-empty datasets). - Added `test_unify_block_metadata_schema_all_empty_blocks` (fallback + precedence). - Ran locally against master with the Ray nightly wheel + `setup-dev.py` symlinks: - `pytest python/ray/data/tests/test_util.py` → 39 passed - `pytest python/ray/data/tests/test_arrow_block.py -k to_pandas` → 13 passed - Issue's exact repro passes. ### Notes for reviewers / AI-assistance disclosure - This PR was prepared with AI assistance; I have reviewed every changed line and run the tests above locally. - Duplicate-work check: no other open PR references ray-project#59946; the only prior PR was my own ray-project#64721, which this supersedes. --------- Signed-off-by: lonexreb <[email protected]> Signed-off-by: iamjustinhsu <[email protected]> Co-authored-by: iamjustinhsu <[email protected]>

Why are these changes needed?
Dataset.to_pandas()drops columns for an empty dataset:to_pandas()builds the result by iteratingiter_batches, which yields no batches for an empty dataset.PandasBlockBuilder.build()then produces a DataFrame with zero columns, even though the dataset's schema (apples: int32) is known.The fix: when the built DataFrame has no columns, reconstruct the columns — and dtypes, when the underlying schema is an Arrow schema (via
base_schema.empty_table()) — from the dataset schema.Verification
Built
masterfrom source and confirmed:["apples"](was[]).["a", "b"]preserved.Related issue number
Closes #59946
Checks
git commit -s) so that DCO passes.test_to_pandas_empty_dataset_preserves_columnsintest_arrow_block.py(single- and multi-column empty tables). Fails on current master, passes with this fix.