Created
February 9, 2021 17:25
-
-
Save toinsson/62898ebd50c1d778c44be85803c71d79 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import reduce | |
from operator import and_, or_ | |
def select(df, **kwargs): | |
'''Builds a boolean array where columns indicated by keys in kwargs are tested for equality to their values. | |
In the case where a value is a list, a logical or is performed between the list of resulting boolean arrays. | |
Finally, a logical and is performed between all boolean arrays. | |
''' | |
res = [] | |
for k, v in kwargs.items(): | |
# TODO: if iterable, expand with list(iter) | |
# multiple column selection with logical or | |
if isinstance(v, list): | |
res_or = [] | |
for w in v: | |
res_or.append(df[k] == w) | |
res_or = reduce(lambda x, y: or_(x,y), res_or) | |
res.append(res_or) | |
# single column selection | |
else: | |
res.append(df[k] == v) | |
# logical and | |
if res: | |
res = reduce(lambda x, y: and_(x,y), res) | |
res = df[res] | |
else: | |
res = df | |
return res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment