Skip to content

BUG: Fix bug in loc setitem changing the dtype when condition is False #37672

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 30 commits into from
Dec 13, 2021

Conversation

phofl
Copy link
Member

@phofl phofl commented Nov 6, 2020

This fixes the bug, but I am not sure, if the solution is good enough....

@phofl phofl added the Indexing Related to indexing on series/frames, not to indexes themselves label Nov 6, 2020
@rhshadrach rhshadrach added the Bug label Nov 6, 2020
else:
# e.g. we are bool dtype and value is nan
# TODO: watch out for case with listlike value and scalar/empty indexer
if is_list_like(value) and is_empty_indexer(indexer, np.array(value)):
Copy link
Contributor

Choose a reason for hiding this comment

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

can you put this as another elif case

Copy link
Member Author

Choose a reason for hiding this comment

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

Done

@@ -920,10 +920,11 @@ def setitem(self, indexer, value):

elif lib.is_scalar(value) and not isna(value):
dtype, _ = infer_dtype_from_scalar(value, pandas_dtype=True)

elif is_list_like(value) and is_empty_indexer(indexer, np.array(value)):
Copy link
Member

Choose a reason for hiding this comment

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

any way to avoid the np.array call? i think that makes a copy if we have eg a list

Copy link
Member Author

@phofl phofl Nov 8, 2020

Choose a reason for hiding this comment

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

I don't think so, is_empty_indexer requires an ndarray, while value may be a list.

Copy link
Member

Choose a reason for hiding this comment

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

the test is for loc.__setitem__. is that (or i guess iloc.__setitem__) the only way we can get here? it may make sense to do this in setitem_with_indexer

Copy link
Member Author

Choose a reason for hiding this comment

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

Yeah, that would be possible I think.
Sport would be in

for i, idx in enumerate(indexer):

Ran the tests in indexing, frame/indexing and series/indexing locally, this seems to work. Let me know, if we should move this

Copy link
Contributor

Choose a reason for hiding this comment

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

you can use np.asarray, also can we check len of the indexer here first to short-cut?

Copy link
Member Author

Choose a reason for hiding this comment

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

Thx used asarray. Indexer is a tuple containing an empty list, len does not work here unfortunately.

@@ -298,6 +298,13 @@ def test_iloc_setitem_bool_indexer(self, klass):
expected = DataFrame({"flag": ["x", "y", "z"], "value": [2, 3, 4]})
tm.assert_frame_equal(df, expected)

def test_setitem_only_false_indexer_dtype_changed(self):
Copy link
Member

Choose a reason for hiding this comment

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

can you put this below in the class TestDataFrameSetItemBooleanMask?

which part(s) of the line df.loc[[False], ["b"]] = 10 - df["c"] are relevant to the bugfix here? e.g. does it matter that the right hand side is a Series? Would this be testing the right thing if it were series.loc[[False]]?

Copy link
Member Author

Choose a reason for hiding this comment

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

df.loc[[False], ["b"]] = 10 did not trigger the error. We need a Series on the rhs.

Copy link
Member Author

Choose a reason for hiding this comment

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

Moved the test

@@ -469,6 +469,7 @@ Indexing
- Bug in :meth:`Index.where` incorrectly casting numeric values to strings (:issue:`37591`)
- Bug in :meth:`Series.loc` and :meth:`DataFrame.loc` raises when numeric label was given for object :class:`Index` although label was in :class:`Index` (:issue:`26491`)
- Bug in :meth:`DataFrame.loc` returned requested key plus missing values when ``loc`` was applied to single level from :class:`MultiIndex` (:issue:`27104`)
- Bug in :meth:`DataFrame.loc.__setitem__` changed dtype when indexer was completely ``False`` (:issue:`37550`)
Copy link
Member

Choose a reason for hiding this comment

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

changed -> changing

these should usually be participles

Copy link
Member Author

Choose a reason for hiding this comment

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

Thx, will follow this in the future

@@ -339,3 +339,13 @@ def test_setitem_boolean_mask(self, mask_type, float_frame):
expected = df.copy()
expected.values[np.array(mask)] = np.nan
tm.assert_frame_equal(result, expected)

def test_setitem_only_false_indexer_dtype_changed(self):
Copy link
Member

Choose a reason for hiding this comment

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

can you comment and/or edit the test name to make clear

  • is iloc affected?
  • does it matter that you have ["b"] instead of, say, "b" or ":"?

comment that the bug is for the value being set being a Series obj

Copy link
Member

Choose a reason for hiding this comment

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

is Series affected?

Copy link
Member Author

Choose a reason for hiding this comment

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

Series is not affected. Goes only wrong with ["b"]

Iloc is actually also affected, but has to be fixed differently probably. In case of loc we get an empty indexer. In case of iloc we get an indexer like ([False],), which is not empty per is_empty_indexer. We could adjust is_empty_indexer or we have to go a different way here

@@ -920,10 +920,11 @@ def setitem(self, indexer, value):

elif lib.is_scalar(value) and not isna(value):
dtype, _ = infer_dtype_from_scalar(value, pandas_dtype=True)

elif is_list_like(value) and is_empty_indexer(indexer, np.array(value)):
Copy link
Contributor

Choose a reason for hiding this comment

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

you can use np.asarray, also can we check len of the indexer here first to short-cut?

expected = DataFrame({"a": ["a"], "b": [1], "c": [1]})
tm.assert_frame_equal(df, expected)

df.loc[[False], ["b"]] = 10 - 1
Copy link
Member

Choose a reason for hiding this comment

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

you can simplify to 9

Copy link
Member Author

Choose a reason for hiding this comment

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

Thx

# GH#37550
# Dtype is only changed when value to set is a Series
df = DataFrame({"a": ["a"], "b": [1], "c": [1]})
df.loc[[False], ["b"]] = 10 - df["c"]
Copy link
Member

Choose a reason for hiding this comment

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

can you make clear either in the test name and/or comment that/whether the type of indexer for ["b"] is relevant

Copy link
Member Author

Choose a reason for hiding this comment

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

Added comment and parametrized test

@@ -928,10 +928,11 @@ def setitem(self, indexer, value):

elif lib.is_scalar(value) and not isna(value):
dtype, _ = infer_dtype_from_scalar(value, pandas_dtype=True)

elif is_list_like(value) and is_empty_indexer(indexer, np.asarray(value)):
Copy link
Member

Choose a reason for hiding this comment

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

im not sure this is the right place to catch this, since i think we are specifically interested in all-False boolean indexers coming through loc. does this get here via setitem_with_indexer, and if so, can you point out specifically which branch(es)?

Copy link
Member Author

Choose a reason for hiding this comment

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

Through _setitem_with_indexer_split_path -> _setitem_with_indexer_2d_value -> _setitem_single_column

as mentioned in #37672 (comment) we could do that in setitem_with_indexer if this is better

Copy link
Member

Choose a reason for hiding this comment

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

In _setitem_with_indexer_split_path L 1686-1688 we have a no-op block that is for all-false boolean masks. could move it up to before the 2D check. would that do the trick?

Copy link
Member Author

Choose a reason for hiding this comment

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

One possible solution is moving up the lplane_indexer==0 condition and removing the value part. Probably the shortest and does not seem to break tests. Don't know if this kills behavior not tested, but if indexer has len=0, we probably do not want to set values anyway

expected = DataFrame({"a": ["a"], "b": [1], "c": [1]})
tm.assert_frame_equal(df, expected)

df.loc[[False], ["b"]] = 9
Copy link
Member

Choose a reason for hiding this comment

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

should [False] be func(value) as above? if not, this might belong as a separate test

@jreback
Copy link
Contributor

jreback commented May 21, 2021

@phofl can you rebase and will look again

@phofl
Copy link
Member Author

phofl commented May 23, 2021

merged master

@jreback jreback added this to the 1.3 milestone May 24, 2021
@jreback
Copy link
Contributor

jreback commented May 26, 2021

@jbrockmendel ok here?

@jreback
Copy link
Contributor

jreback commented May 31, 2021

@phofl can you update

@jbrockmendel
Copy link
Member

Looks like the ser[[]] = [1, 2, 3] thing hasnt been addressed

@jreback jreback removed this from the 1.3 milestone May 31, 2021
@jreback
Copy link
Contributor

jreback commented May 31, 2021

ok let's move off the milestone for rn, can always do after the rc

@jreback
Copy link
Contributor

jreback commented Oct 4, 2021

@phofl status of this (merge master)

@jreback
Copy link
Contributor

jreback commented Nov 28, 2021

@phofl worth fixing up?

@phofl
Copy link
Member Author

phofl commented Nov 28, 2021

Yeah definitely.

i hope that I can get back to this friday or friday next week

# Conflicts:
#	doc/source/whatsnew/v1.3.0.rst
#	pandas/core/indexing.py
@phofl
Copy link
Member Author

phofl commented Dec 10, 2021

I moved the fix for the all False case. This fixes an inconsistency in _align_series and covers the all False indexer case.

I could not figure the empty list thing out. The values look exactly the same as in the all False case. We probably will have to fix this someplace else, but not sure right now.

I woild propose open an issue about that and go from there.

@jreback jreback added this to the 1.4 milestone Dec 10, 2021
@jreback
Copy link
Contributor

jreback commented Dec 10, 2021

lgtm @jbrockmendel if any comments

@jbrockmendel
Copy link
Member

will take a look this afternoon. (got booster yesterday, moving slow today)

@@ -2058,6 +2058,8 @@ def ravel(i):
# we have a frame, with multiple indexers on both axes; and a
# series, so need to broadcast (see GH5206)
if sum_aligners == self.ndim and all(is_sequence(_) for _ in indexer):
if is_empty_indexer(indexer[0], ser._values):
return ser._values.copy()
Copy link
Member

Choose a reason for hiding this comment

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

evidently it works, but this seems like a weird place to handle this. is my intuition wrong here?

Copy link
Member Author

Choose a reason for hiding this comment

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

This ensures, that an indexer like (np.array([]), np.array([1])) is handled the same as (np.array([]), 1), hence I handled it here.

@jbrockmendel
Copy link
Member

Does this relate to #43632?

@phofl
Copy link
Member Author

phofl commented Dec 11, 2021

I don't think so. The all False case is an empty not a boolean indexer when jumping into the setitem logic

def test_setitem_loc_empty_indexer_raises_with_non_empty_value(self, box):
# GH#37672
df = DataFrame({"a": ["a"], "b": [1], "c": [1]})
if box == Series:
Copy link
Member

Choose a reason for hiding this comment

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

nitpick "box is Series", i can change this in my next CLN branch

Copy link
Member

@jbrockmendel jbrockmendel left a comment

Choose a reason for hiding this comment

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

LGTM

@jreback jreback merged commit 776857a into pandas-dev:master Dec 13, 2021
@jreback
Copy link
Contributor

jreback commented Dec 13, 2021

thanks @phofl

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Indexing Related to indexing on series/frames, not to indexes themselves
Projects
None yet
Development

Successfully merging this pull request may close these issues.

BUG: Loc changes dtype when condition is completly False
5 participants