Skip to content

[Data] Preserve schema columns in to_pandas() for empty datasets - #64721

Closed
lonexreb wants to merge 3 commits into
ray-project:masterfrom
lonexreb:fix/59946-to-pandas-empty-columns
Closed

lonexreb wants to merge 3 commits into
ray-project:masterfrom
lonexreb:fix/59946-to-pandas-empty-columns

Conversation

@lonexreb

Copy link
Copy Markdown
Contributor

Why are these changes needed?

Dataset.to_pandas() drops columns for an empty dataset:

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: columns == []

to_pandas() builds the result by iterating iter_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 master from source and confirmed:

  • Issue's repro: ["apples"] (was []).
  • Empty multi-column table: ["a", "b"] preserved.
  • Non-empty datasets: unchanged (columns and row counts correct).

Related issue number

Closes #59946

Checks

  • I've signed off every commit (git commit -s) so that DCO passes.
  • I've made sure the tests are passing.
  • Testing Strategy
    • Unit tests: added test_to_pandas_empty_dataset_preserves_columns in test_arrow_block.py (single- and multi-column empty tables). Fails on current master, passes with this fix.

`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]>
@lonexreb
lonexreb requested a review from a team as a code owner July 13, 2026 19:28
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

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

Comment thread python/ray/data/dataset.py Outdated
Comment on lines +6814 to +6820
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))

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.

medium

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))

Comment on lines +357 to +374
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"]

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.

medium

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) == 0

Address 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]>
@lonexreb

Copy link
Copy Markdown
Contributor Author

Good suggestions, thanks — done. The pandas-backed fallback now preserves per-column dtypes via PandasBlockSchema.types (instead of defaulting to object), and I expanded test_to_pandas_empty_dataset_preserves_columns to assert dtypes for both Arrow-backed (int32) and Pandas-backed (int64/float64) empty datasets. Pushed.

@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

Reviewed by Cursor Bugbot for commit 15a3f8f. Configure here.

Comment thread python/ray/data/dataset.py Resolved
… 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]>
@lonexreb

Copy link
Copy Markdown
Contributor Author

Good catch — you're right that empty_table().to_pandas() bypassed the BlockAccessor conversion, so the empty result used numpy int32 while a non-empty to_pandas() yields int32[pyarrow]. Fixed by routing the empty Arrow table through BlockAccessor.for_block(...).to_pandas(), and updated the test to assert the empty dtype matches a non-empty dataset of the same schema. Pushed.

@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Jul 14, 2026
@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 Jul 28, 2026
@github-actions

Copy link
Copy Markdown

This pull request has been automatically closed because there has been no more activity in the 14 days
since being marked stale.

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!

@github-actions github-actions Bot closed this Aug 12, 2026
richardliaw pushed a commit that referenced this pull request Oct 6, 2026
…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]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…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]>
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 stale The issue is stale. It will be closed within 7 days unless there are further conversation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Data] from_arrow_refs converts an empty table with one column into an empty table with zero columns

1 participant