From 04494c43ea4db2891b86870875eba5bb2d06ee5f Mon Sep 17 00:00:00 2001 From: Patrick Hoefler Date: Mon, 5 Dec 2022 12:45:42 +0100 Subject: [PATCH] BUG: loc.setitem raising when expanding empty frame with array value --- doc/source/whatsnew/v2.0.0.rst | 1 + pandas/core/indexing.py | 4 +++- pandas/tests/frame/indexing/test_indexing.py | 7 +++++++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index b1400be59b3a1..6c510496f0c61 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -707,6 +707,7 @@ Indexing - Bug in :meth:`DataFrame.loc` coercing dtypes when setting values with a list indexer (:issue:`49159`) - Bug in :meth:`DataFrame.loc` raising ``ValueError`` with ``bool`` indexer and :class:`MultiIndex` (:issue:`47687`) - Bug in :meth:`DataFrame.__setitem__` raising ``ValueError`` when right hand side is :class:`DataFrame` with :class:`MultiIndex` columns (:issue:`49121`) +- Bug in :meth:`DataFrame.loc` when expanding an empty DataFrame and setting an array-like value (:issue:`49972`) - Bug in :meth:`DataFrame.reindex` casting dtype to ``object`` when :class:`DataFrame` has single extension array column when re-indexing ``columns`` and ``index`` (:issue:`48190`) - Bug in :func:`~DataFrame.describe` when formatting percentiles in the resulting index showed more decimals than needed (:issue:`46362`) - Bug in :meth:`DataFrame.compare` does not recognize differences when comparing ``NA`` with value in nullable dtypes (:issue:`48939`) diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 929a1c4e30a5f..280cad1311299 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1736,7 +1736,9 @@ def _setitem_with_indexer(self, indexer, value, name: str = "iloc"): arr = extract_array(value, extract_numpy=True) taker = -1 * np.ones(len(self.obj), dtype=np.intp) empty_value = algos.take_nd(arr, taker) - if not isinstance(value, ABCSeries): + if not isinstance(value, ABCSeries) and not isinstance( + indexer[0], dict + ): # if not Series (in which case we need to align), # we can short-circuit empty_value[indexer[0]] = arr diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index 81a5e3d9947be..ab2e7affdfedf 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -1737,6 +1737,13 @@ def test_getitem_preserve_object_index_with_dates(self, indexer): assert ser.index.dtype == object + def test_loc_setitem_empty_frame_expansion(self): + # GH#49972 + result = DataFrame() + result.loc[0, 0] = np.asarray([0]) + expected = DataFrame({0: [0.0]}) + tm.assert_frame_equal(result, expected) + def test_loc_on_multiindex_one_level(self): # GH#45779 df = DataFrame(