Skip to content

Commit

Permalink
fix(python): Fix DataFrame.to_arrow() for 0x0 dataframes
Browse files Browse the repository at this point in the history
No schema can be inferred from the batches, as `._df.to_arrow()` returns an empty list. `pa.Tables.from_batches()` requires a schema if no batches are passed in.

Closes pola-rs#8884.
  • Loading branch information
zundertj committed May 31, 2023
1 parent 4fca1ae commit 39db5dc
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
7 changes: 5 additions & 2 deletions py-polars/polars/dataframe/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -1845,8 +1845,11 @@ def to_arrow(self) -> pa.Table:
bar: [["a","b","c","d","e","f"]]
"""
record_batches = self._df.to_arrow()
return pa.Table.from_batches(record_batches)
if self.shape[1]: # all except 0x0 dataframe
record_batches = self._df.to_arrow()
return pa.Table.from_batches(record_batches)
else: # 0x0 dataframe, cannot infer schema from batches
return pa.table({})

@overload
def to_dict(self, as_series: Literal[True] = ...) -> dict[str, Series]:
Expand Down
17 changes: 17 additions & 0 deletions py-polars/tests/unit/test_interop.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,23 @@ def test_arrow_null_roundtrip() -> None:
assert c1.to_pylist() == c2.to_pylist()


def test_arrow_empty_dataframe() -> None:
# 0x0 dataframe
df = pl.DataFrame({})
tbl = pa.table({})
assert df.to_arrow() == tbl
df2 = cast(pl.DataFrame, pl.from_arrow(df.to_arrow()))
assert_frame_equal(df2, df)

# 0 row dataframe
df = pl.DataFrame({}, schema={"a": pl.Int32})
tbl = pa.Table.from_batches([], pa.schema([pa.field("a", pa.int32())]))
assert df.to_arrow() == tbl
df2 = cast(pl.DataFrame, pl.from_arrow(df.to_arrow()))
assert df2.schema == {"a": pl.Int32}
assert df2.shape == (0, 1)


def test_arrow_dict_to_polars() -> None:
pa_dict = pa.DictionaryArray.from_arrays(
indices=np.array([0, 1, 2, 3, 1, 0, 2, 3, 3, 2]),
Expand Down

0 comments on commit 39db5dc

Please sign in to comment.