You can filter by multiple columns (more than two) using the np.logical_and operator to replace & (or np.logical_or to replace | )
Here is an example of a function that does this work if you provide target values ββfor multiple fields. You can adapt it for different types of filtering and the like:
def filter_df(df, filter_values): """Filter df by matching targets for multiple columns. Args: df (pd.DataFrame): dataframe filter_values (None or dict): Dictionary of the form: '{<field>: <target_values_list>}' used to filter columns data. """ import numpy as np if filter_values is None or not filter_values: return df return df[ np.logical_and.reduce([ df[column].isin(target_values) for column, target_values in filter_values.items() ]) ]
Using:
df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [1, 2, 3, 4]}) filter_df(df, { 'a': [1, 2, 3], 'b': [1, 2, 4] })
Tom Bug Sep 06 '19 at 13:26 2019-09-06 13:26
source share