Skip to content

Commit

Permalink
Add callable filters to isin selector (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
coroa authored May 22, 2023
1 parent dfe5ab7 commit 1583a04
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 2 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
Changelog
=========

* :func:`~selectors.isin` accepts callable filters :pull:`16`, f.ex.
``df.loc[isin(year=lambda s: s>2000)]``
* New function :func:`~core.concat` makes concatenation level aware :pull:`14`

v0.2.5 (2023-05-04)
Expand Down
9 changes: 7 additions & 2 deletions src/pandas_indexing/selectors.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,12 @@ def __call__(self, df):
if self.ignore_missing_levels:
filters = {k: v for k, v in filters.items() if k in index.names}

tests = (index.isin(np.atleast_1d(v), level=k) for k, v in filters.items())
return reduce(and_, tests)
def apply_filter(value, level):
if callable(value):
return value(index.get_level_values(level))
return index.isin(np.atleast_1d(value), level=level)

return reduce(and_, (apply_filter(v, k) for k, v in filters.items()))


def isin(
Expand All @@ -101,6 +105,7 @@ def isin(
If set, levels missing in data index will be ignored
**filters
Filter to apply on given levels (lists are ``or`` ed, levels are ``and`` ed)
Callables are evaluated on the index level values.
Returns
-------
Expand Down
3 changes: 3 additions & 0 deletions tests/test_selectors.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ def test_isin_mseries(mseries: Series):
sel = isin(num=[2, 3], str="foo")
assert_series_equal(mseries.loc[sel], mseries.iloc[[1]])

sel = isin(num=lambda s: s > 1)
assert_series_equal(mseries.loc[sel], mseries.iloc[[1, 2]])


def test_isin_ignore_missing_levels(mseries: Series):
sel = isin(str="foo", bla=False)
Expand Down

0 comments on commit 1583a04

Please sign in to comment.