Skip to content

Commit 79df665

Browse files
authored
GH4228 Clearer error on scalar to dataframe (#4533)
* GH4228 Clearer error on scalar to dataframe * GH4228 Add change to Documentation
1 parent 1597e3a commit 79df665

File tree

3 files changed

+7
-0
lines changed

3 files changed

+7
-0
lines changed

doc/whats-new.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,8 @@ Bug fixes
5454
Documentation
5555
~~~~~~~~~~~~~
5656

57+
- Raise a more informative error when :py:meth:`DataArray.to_dataframe` is
58+
is called on a scalar (:issue:`4228`). By `Pieter Gijsbers <https://github.com/pgijsbers>`_.
5759

5860
Internal Changes
5961
~~~~~~~~~~~~~~~~

xarray/core/dataarray.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2442,6 +2442,8 @@ def to_dataframe(
24422442
"cannot convert an unnamed DataArray to a "
24432443
"DataFrame: use the ``name`` parameter"
24442444
)
2445+
if self.ndim == 0:
2446+
raise ValueError("cannot convert a scalar to a DataFrame")
24452447

24462448
# By using a unique name, we can convert a DataArray into a DataFrame
24472449
# even if it shares a name with one of its coordinates.

xarray/tests/test_dataarray.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3538,6 +3538,9 @@ def test_to_dataframe(self):
35383538
with pytest.raises(ValueError, match="does not match the set of dimensions"):
35393539
arr.to_dataframe(dim_order=["B", "A", "C"])
35403540

3541+
with pytest.raises(ValueError, match=r"cannot convert a scalar"):
3542+
arr.sel(A="c", B=2).to_dataframe()
3543+
35413544
arr.name = None # unnamed
35423545
with raises_regex(ValueError, "unnamed"):
35433546
arr.to_dataframe()

0 commit comments

Comments
 (0)