select - python pandas index dataframe using a dict -


consider having dataframe columns 'a', 'b' , 'c'.

i select rows dataframe using dict of form {'a':1, 'b':2}. should give me rows a=1 , b=2.

also dict changing dynamically don't know in advance columns need queried. might {'a':1, 'c':2} @ iteration.

you can use .groupby.filter() function.

import pandas pd import numpy np  # data # ============================= np.random.seed() = np.random.randint(1, 5, 100) b = np.random.randint(1, 5, 100) c = np.random.randint(1, 5, 100) df = pd.dataframe(dict(a=a,b=b,c=c)) print(df)       b  c 0   3  4  4 1   2  2  4 2   2  2  4 3   3  1  1 4   2  4  2 5   3  3  2 6   1  1  3 7   3  3  3 8   4  4  4 9   2  4  3 .. .. .. .. 90  3  1  3 91  3  2  3 92  1  1  1 93  1  2  3 94  3  2  2 95  2  4  1 96  4  2  3 97  4  2  4 98  1  2  3 99  1  4  3  [100 rows x 3 columns]   # processing # ===================== my_dict = {'a':1, 'b':2}  df.groupby(level=0).filter(lambda row: (row.a == my_dict['a']) & (row.b == my_dict['b']))       b  c 41  1  2  1 43  1  2  2 53  1  2  4 67  1  2  1 93  1  2  3 98  1  2  3 

Comments