Skip to content

Commit

Permalink
ENH: tweaks to Series.where #2337
Browse files Browse the repository at this point in the history
  • Loading branch information
changhiskhan committed Nov 24, 2012
1 parent 36fd857 commit 6876c17
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 3 deletions.
1 change: 1 addition & 0 deletions RELEASE.rst
Expand Up @@ -30,6 +30,7 @@ pandas 0.10.0
**New features**

- Add error handling to Series.str.encode/decode (#2276)
- Add ``where`` and ``mask`` to Series (#2337)

**API Changes**

Expand Down
16 changes: 14 additions & 2 deletions pandas/core/series.py
Expand Up @@ -575,15 +575,27 @@ def where(self, cond, other=nan, inplace=False):
-------
wh: Series
"""
if isinstance(cond, Series):
cond = cond.reindex(self.index, fill_value=True)
if not hasattr(cond, 'shape'):
raise ValueError('where requires an ndarray like object for its '
'condition')
if len(cond) != len(self):
raise ValueError('condition must have same length as series')

if inplace:
ser = self if inplace else self.copy()
if not isinstance(other, (list, tuple, np.ndarray)):
self._set_with(~cond, other)
return self

This comment has been minimized.

Copy link
@jreback

jreback Nov 24, 2012

Contributor

shouldn't this be ser? and not self, as inplace = False with a scalar (eg nan) will hit this and shouldn't modify the original series but the copy (which is what ser is here)

This comment has been minimized.

Copy link
@changhiskhan

changhiskhan Nov 24, 2012

Author Contributor

yes, you're right. fixing right now

This comment has been minimized.

Copy link
@changhiskhan

changhiskhan Nov 24, 2012

Author Contributor

Just pushed to master and also added a test case.
Thanks!!


return self._get_values(cond).reindex_like(self).fillna(other)
if isinstance(other, Series):
other = other.reindex(ser.index)
if len(other) != len(ser):
raise ValueError('Length of replacements must equal series length')

np.putmask(ser, ~cond, other)

return ser

def mask(self, cond):
"""
Expand Down
13 changes: 12 additions & 1 deletion pandas/tests/test_series.py
Expand Up @@ -953,15 +953,26 @@ def test_where(self):
rs = s.where(cond)
assert(s.shape == rs.shape)

rs = s.where(cond[:3], -s)
assert_series_equal(rs, s.abs()[:3].append(s[3:]))

self.assertRaises(ValueError, s.where, 1)
self.assertRaises(ValueError, s.where, cond[:3].values, -s)
self.assertRaises(ValueError, s.where, cond, s[:3].values)

def test_where_inplace(self):
s = Series(np.random.randn(5))
cond = s > 0

rs = s.copy()
rs.where(cond,inplace=True)
rs.where(cond, inplace=True)
assert_series_equal(rs.dropna(), s[cond])
assert_series_equal(rs, s.where(cond))

rs = s.copy()
rs.where(cond, -s, inplace=True)
assert_series_equal(rs, s.where(cond, -s))


def test_mask(self):
s = Series(np.random.randn(5))
Expand Down

0 comments on commit 6876c17

Please sign in to comment.