From 30c7a0553aaa5d31c1937c77b5858e4098a93a62 Mon Sep 17 00:00:00 2001 From: Kilian Lieret Date: Thu, 10 Jun 2021 11:44:28 +0200 Subject: [PATCH] BUG: Scalar assignment to empty dataframe with loc. Closes GH41891 This weakens a check introduced in 7bbeb79297532d209d67f7bdc61394ddee3acbb1 which caused ValueErrors for df[:, 1] = 1 if df is an empty DataFrame. With this commit no error is thrown and the column is added to the dataframe (which remains empty). --- pandas/core/indexing.py | 9 +++++---- pandas/tests/indexing/test_partial.py | 6 +++++- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 3707e141bc447..b25e7a5afd660 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1646,10 +1646,11 @@ def _setitem_with_indexer(self, indexer, value, name="iloc"): if self.ndim > 1 and i == info_axis: # add the new item, and set the value - # must have all defined axes if we have a scalar - # or a list-like on the non-info axes if we have a - # list-like - if not len(self.obj): + # If we have a scalar as values, must have all defined + # axes or be an empty slice. + # If we have a list-like as value, must have a + # list-like on the non-info axes + if not len(self.obj) and not com.is_null_slice(indexer[0]): if not is_list_like_indexer(value): raise ValueError( "cannot set a frame with no " diff --git a/pandas/tests/indexing/test_partial.py b/pandas/tests/indexing/test_partial.py index 693e67652c912..b16f802a982dd 100644 --- a/pandas/tests/indexing/test_partial.py +++ b/pandas/tests/indexing/test_partial.py @@ -384,7 +384,11 @@ def test_partial_set_empty_frame(self): msg = "cannot set a frame with no defined index and a scalar" with pytest.raises(ValueError, match=msg): - df.loc[:, 1] = 1 + df.loc[3:4, 1] = 1 + + df.loc[:, 1] = 1 + assert df.columns.to_list() == [1] + assert len(df) == 0 def test_partial_set_empty_frame2(self): # these work as they don't really change