Skip to content

Commit f86f9f2

Browse files
eshareadymroeschke
andauthored
BUG: Setting values on DataFrame with multi-index .loc(axis=0) access adds columns (#58301)
* fixed the issue by making sure setting an item takes into account the axis argument if supplied to loc. added a test checking for this based on the github issue as well * Running pre commit checks * Pre commit checks * Update doc/source/whatsnew/v3.0.0.rst Co-authored-by: Matthew Roeschke <[email protected]> --------- Co-authored-by: Matthew Roeschke <[email protected]>
1 parent e60bb8e commit f86f9f2

File tree

3 files changed

+29
-4
lines changed

3 files changed

+29
-4
lines changed

doc/source/whatsnew/v3.0.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -397,7 +397,7 @@ Missing
397397

398398
MultiIndex
399399
^^^^^^^^^^
400-
-
400+
- :func:`DataFrame.loc` with ``axis=0`` and :class:`MultiIndex` when setting a value adds extra columns (:issue:`58116`)
401401
-
402402

403403
I/O

pandas/core/indexing.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -757,7 +757,7 @@ def _get_setitem_indexer(self, key):
757757
"""
758758
if self.name == "loc":
759759
# always holds here bc iloc overrides _get_setitem_indexer
760-
self._ensure_listlike_indexer(key)
760+
self._ensure_listlike_indexer(key, axis=self.axis)
761761

762762
if isinstance(key, tuple):
763763
for x in key:
@@ -857,8 +857,10 @@ def _ensure_listlike_indexer(self, key, axis=None, value=None) -> None:
857857
if isinstance(key, tuple) and len(key) > 1:
858858
# key may be a tuple if we are .loc
859859
# if length of key is > 1 set key to column part
860-
key = key[column_axis]
861-
axis = column_axis
860+
# unless axis is already specified, then go with that
861+
if axis is None:
862+
axis = column_axis
863+
key = key[axis]
862864

863865
if (
864866
axis == column_axis

pandas/tests/indexing/multiindex/test_loc.py

+23
Original file line numberDiff line numberDiff line change
@@ -381,6 +381,29 @@ def test_multiindex_setitem_columns_enlarging(self, indexer, exp_value):
381381
)
382382
tm.assert_frame_equal(df, expected)
383383

384+
def test_multiindex_setitem_axis_set(self):
385+
# GH#58116
386+
dates = pd.date_range("2001-01-01", freq="D", periods=2)
387+
ids = ["i1", "i2", "i3"]
388+
index = MultiIndex.from_product([dates, ids], names=["date", "identifier"])
389+
df = DataFrame(0.0, index=index, columns=["A", "B"])
390+
df.loc(axis=0)["2001-01-01", ["i1", "i3"]] = None
391+
392+
expected = DataFrame(
393+
[
394+
[None, None],
395+
[0.0, 0.0],
396+
[None, None],
397+
[0.0, 0.0],
398+
[0.0, 0.0],
399+
[0.0, 0.0],
400+
],
401+
index=index,
402+
columns=["A", "B"],
403+
)
404+
405+
tm.assert_frame_equal(df, expected)
406+
384407
def test_sorted_multiindex_after_union(self):
385408
# GH#44752
386409
midx = MultiIndex.from_product(

0 commit comments

Comments
 (0)