Skip to content

BUG: loc.setitem with expansion expanding rows #37932

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
Nov 27, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
7 changes: 7 additions & 0 deletions pandas/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1684,6 +1684,13 @@ def _setitem_with_indexer_split_path(self, indexer, value):
for loc, v in zip(ilocs, value):
self._setitem_single_column(loc, v, pi)

elif len(ilocs) == 1 and com.is_null_slice(pi) and len(self.obj) == 0:
# This is a setitem-with-expansion, see
# test_loc_setitem_empty_append_expands_rows
# e.g. df = DataFrame(columns=["x", "y"])
# df.loc[:, "x"] = [1, 2, 3]
self._setitem_single_column(ilocs[0], value, pi)

else:
raise ValueError(
"Must have equal len keys and value "
Expand Down
9 changes: 8 additions & 1 deletion pandas/tests/indexing/test_loc.py
Original file line number Diff line number Diff line change
Expand Up @@ -942,7 +942,7 @@ def test_loc_uint64(self):
result = s.loc[[np.iinfo("uint64").max - 1, np.iinfo("uint64").max]]
tm.assert_series_equal(result, s)

def test_loc_setitem_empty_append(self):
def test_loc_setitem_empty_append_expands_rows(self):
# GH6173, various appends to an empty dataframe

data = [1, 2, 3]
Expand All @@ -953,6 +953,13 @@ def test_loc_setitem_empty_append(self):
df.loc[:, "x"] = data
tm.assert_frame_equal(df, expected)

# same thing, but with mixed dtypes
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

make a separate test

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated+green

df = DataFrame(columns=["x", "y"])
df["x"] = df["x"].astype(np.int64)
df.loc[:, "x"] = data
tm.assert_frame_equal(df, expected)

def test_loc_setitem_empty_append_single_value(self):
# only appends one value
expected = DataFrame({"x": [1.0], "y": [np.nan]})
df = DataFrame(columns=["x", "y"], dtype=float)
Expand Down