Skip to content

BUG: Setting values on DataFrame with multi-index .loc(axis=0) access adds columns #58301

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Apr 18, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -397,7 +397,7 @@ Missing

MultiIndex
^^^^^^^^^^
-
- Bug in :func:`_LocationIndexer.__setitem__` where columns were added when they shouldn't be when using :func:`DataFrame.loc` with a multi index and specified axis (:issue:`58116`)
-

I/O
Expand Down
8 changes: 5 additions & 3 deletions pandas/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -757,7 +757,7 @@ def _get_setitem_indexer(self, key):
"""
if self.name == "loc":
# always holds here bc iloc overrides _get_setitem_indexer
self._ensure_listlike_indexer(key)
self._ensure_listlike_indexer(key, axis=self.axis)

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

if (
axis == column_axis
Expand Down
23 changes: 23 additions & 0 deletions pandas/tests/indexing/multiindex/test_loc.py
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,29 @@ def test_multiindex_setitem_columns_enlarging(self, indexer, exp_value):
)
tm.assert_frame_equal(df, expected)

def test_multiindex_setitem_axis_set(self):
# GH#58116
dates = pd.date_range("2001-01-01", freq="D", periods=2)
ids = ["i1", "i2", "i3"]
index = MultiIndex.from_product([dates, ids], names=["date", "identifier"])
df = DataFrame(0.0, index=index, columns=["A", "B"])
df.loc(axis=0)["2001-01-01", ["i1", "i3"]] = None

expected = DataFrame(
[
[None, None],
[0.0, 0.0],
[None, None],
[0.0, 0.0],
[0.0, 0.0],
[0.0, 0.0],
],
index=index,
columns=["A", "B"],
)

tm.assert_frame_equal(df, expected)

def test_sorted_multiindex_after_union(self):
# GH#44752
midx = MultiIndex.from_product(
Expand Down
Loading