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 all 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/v0.18.2.txt
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,7 @@ Other API changes
- ``TimedeltaIndex.astype(int)`` and ``DatetimeIndex.astype(int)`` will now return ``Int64Index`` instead of ``np.array`` (:issue:`13209`)
- ``.filter()`` enforces mutual exclusion of the keyword arguments. (:issue:`12399`)
- ``PeridIndex`` can now accept ``list`` and ``array`` which contains ``pd.NaT`` (:issue:`13430`)
- ``__setitem__`` will no longer apply a callable rhs as a function instead of storing it. Call ``where`` directly to get the previous behavior. (:issue:`13299`)

.. _whatsnew_0182.deprecations:

Expand Down Expand Up @@ -482,7 +483,6 @@ Bug Fixes
- 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 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`)
- Bug in ``DatetimeIndex.is_normalized`` returns incorrectly for normalized date_range in case of local timezones (:issue:`13459`)
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)

def _ensure_valid_index(self, value):
"""
Expand Down
102 changes: 56 additions & 46 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -4419,54 +4419,14 @@ def _align_series(self, other, join='outer', axis=None, level=None,
right = right.fillna(fill_value, method=method, limit=limit)
return left.__finalize__(self), right.__finalize__(other)

_shared_docs['where'] = ("""
Return an object of same shape as self and whose corresponding
entries are from self where cond is %(cond)s and otherwise are from
other.

Parameters
----------
cond : boolean %(klass)s, array or callable
If cond is callable, it is computed on the %(klass)s and
should return boolean %(klass)s or array.
The callable must not change input %(klass)s
(though pandas doesn't check it).

.. versionadded:: 0.18.1

A callable can be used as cond.

other : scalar, %(klass)s, or callable
If other is callable, it is computed on the %(klass)s and
should return scalar or %(klass)s.
The callable must not change input %(klass)s
(though pandas doesn't check it).

.. versionadded:: 0.18.1

A callable can be used as other.

inplace : boolean, default False
Whether to perform the operation in place on the data
axis : alignment axis if needed, default None
level : alignment level if needed, default None
try_cast : boolean, default False
try to cast the result back to the input type (if possible),
raise_on_error : boolean, default True
Whether to raise on invalid data types (e.g. trying to where on
strings)

Returns
-------
wh : same type as caller
""")

@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):
def _where(self, cond, other=np.nan, inplace=False, axis=None, level=None,
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 add a docstring to this one explaining it's purpose?

try_cast=False, raise_on_error=True):
"""
Equivalent to public method `where`, except that `other` is not
applied as a function even if callable. Used in __setitem__.
"""

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

if isinstance(cond, NDFrame):
cond, _ = cond.align(self, join='right', broadcast_axis=1)
Expand Down Expand Up @@ -4622,6 +4582,56 @@ def where(self, cond, other=np.nan, inplace=False, axis=None, level=None,

return self._constructor(new_data).__finalize__(self)

_shared_docs['where'] = ("""
Return an object of same shape as self and whose corresponding
entries are from self where cond is %(cond)s and otherwise are from
other.

Parameters
----------
cond : boolean %(klass)s, array or callable
If cond is callable, it is computed on the %(klass)s and
should return boolean %(klass)s or array.
The callable must not change input %(klass)s
(though pandas doesn't check it).

.. versionadded:: 0.18.1

A callable can be used as cond.

other : scalar, %(klass)s, or callable
If other is callable, it is computed on the %(klass)s and
should return scalar or %(klass)s.
The callable must not change input %(klass)s
(though pandas doesn't check it).

.. versionadded:: 0.18.1

A callable can be used as other.

inplace : boolean, default False
Whether to perform the operation in place on the data
axis : alignment axis if needed, default None
level : alignment level if needed, default None
try_cast : boolean, default False
try to cast the result back to the input type (if possible),
raise_on_error : boolean, default True
Whether to raise on invalid data types (e.g. trying to where on
strings)

Returns
-------
wh : same type as caller
""")

@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):

other = com._apply_if_callable(other, self)
return self._where(cond, other, inplace, axis, level, try_cast,
raise_on_error)

@Appender(_shared_docs['where'] % dict(_shared_doc_kwargs, cond="False"))
def mask(self, cond, other=np.nan, inplace=False, axis=None, level=None,
try_cast=False, raise_on_error=True):
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)
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