Skip to content

BUG: Can't store callables using __setitem__ #13516

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 4 commits into from
Jul 1, 2016
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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v0.18.2.txt
Original file line number Diff line number Diff line change
Expand Up @@ -481,7 +481,7 @@ Bug Fixes
- Bug in ``.tz_convert`` on a tz-aware ``DateTimeIndex`` that relied on index being sorted for correct results (:issue:`13306`)
- Bug in ``pd.read_hdf()`` where attempting to load an HDF file with a single dataset, that had one or more categorical columns, failed unless the key argument was set to the name of the dataset. (:issue:`13231`)
- Bug in ``.rolling()`` that allowed a negative integer window in contruction of the ``Rolling()`` object, but would later fail on aggregation (:issue:`13383`)

- Bug in ``__setitem__`` causing a callable rhs to be applied rather than stored (:issue:`13299`)
Copy link
Contributor

Choose a reason for hiding this comment

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

actually maybe put this in API changes to make it a bit more prominent.


- Bug in various index types, which did not propagate the name of passed index (:issue:`12309`)
- Bug in ``DatetimeIndex``, which did not honour the ``copy=True`` (:issue:`13205`)
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -2395,7 +2395,7 @@ def _setitem_frame(self, key, value):

self._check_inplace_setting(value)
self._check_setitem_copy()
self.where(-key, value, inplace=True)
self.where(-key, value, inplace=True, apply_other=False)

def _ensure_valid_index(self, value):
"""
Expand Down
9 changes: 7 additions & 2 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -4455,6 +4455,9 @@ def _align_series(self, other, join='outer', axis=None, level=None,
raise_on_error : boolean, default True
Whether to raise on invalid data types (e.g. trying to where on
strings)
apply_other : boolean, default True
If False, other will be stored directly rather than applied to
Copy link
Contributor

Choose a reason for hiding this comment

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

I don't think we need another parameter
it's remove the callable check on other entirely

Copy link
Contributor Author

Choose a reason for hiding this comment

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

That's fine with me; I left it in because @sinhrks wanted it for the case where "where" is called directly rather than through setitem.

Copy link
Contributor

Choose a reason for hiding this comment

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

yeah I think we just shouldn't act on other at all.

Copy link
Member

@sinhrks sinhrks Jun 28, 2016

Choose a reason for hiding this comment

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

How about adding internal _where which doesn't apply callable at all? where can use it after applying callable.

I think applying callable to other in where is sometimes useful (described in #13299).

self, even if callable

Returns
-------
Expand All @@ -4463,10 +4466,12 @@ def _align_series(self, other, join='outer', axis=None, level=None,

@Appender(_shared_docs['where'] % dict(_shared_doc_kwargs, cond="True"))
def where(self, cond, other=np.nan, inplace=False, axis=None, level=None,
try_cast=False, raise_on_error=True):
try_cast=False, raise_on_error=True, apply_other=True):

cond = com._apply_if_callable(cond, self)
other = com._apply_if_callable(other, self)

if apply_other:
other = com._apply_if_callable(other, self)

if isinstance(cond, NDFrame):
cond, _ = cond.align(self, join='right', broadcast_axis=1)
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -738,7 +738,7 @@ def setitem(key, value):
if is_bool_indexer(key):
key = check_bool_indexer(self.index, key)
try:
self.where(~key, value, inplace=True)
self.where(~key, value, inplace=True, apply_other=False)
return
except InvalidIndexError:
pass
Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/frame/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,16 @@ def test_setitem_callable(self):
exp = pd.DataFrame({'A': [11, 12, 13, 14], 'B': [5, 6, 7, 8]})
tm.assert_frame_equal(df, exp)

def test_setitem_other_callable(self):
# GH 13299
inc = lambda x: x + 1

df = pd.DataFrame([[-1, 1], [1, -1]])
df[df > 0] = inc

expected = pd.DataFrame([[-1, inc], [inc, -1]])
tm.assert_frame_equal(df, expected)

def test_getitem_boolean(self):
# boolean indexing
d = self.tsframe.index[10]
Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/series/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,16 @@ def test_setitem_callable(self):
s[lambda x: 'A'] = -1
tm.assert_series_equal(s, pd.Series([-1, 2, 3, 4], index=list('ABCD')))

def test_setitem_other_callable(self):
# GH 13299
inc = lambda x: x + 1

s = pd.Series([1, 2, -1, 4])
s[s < 0] = inc

expected = pd.Series([1, 2, inc, 4])
tm.assert_series_equal(s, expected)

def test_slice(self):
numSlice = self.series[10:20]
numSliceEnd = self.series[-10:]
Expand Down