Yank Leo
Yank Leo

Reputation: 582

How to filter pandas dataframe on multiple columns based on a dictionary?

I have 3 dictionaries: A, B, C

and a pandas dataframe with these columns:

['id',
 't1',
 't2',
 't3',
 't4']

Now all I want to do is keep only those rows whose t1 is present in dict A, t2 in dict B and t3 in dict C

I tried dataframe['t1'] in A this gives an error: Series object is mutable cannot be hashed...

Upvotes: 1

Views: 1622

Answers (1)

Sagar Waghmode
Sagar Waghmode

Reputation: 777

You can try something like this.

df.loc[(df['t1'].isin(A.keys()) & df['t2'].isin(B.keys()) & df['t3'].isin(C.keys()))]

I hope this is what you want.

In [51]: df
Out[51]: 
   t1  t2  t3  t4  max_value
0   1   4   5   2          5
1  34  70   1   5         70
2  43  89   4  11         89
3  22  76   4   3         76

In [52]: A = {34: 4}

In [53]: B = {70: 5, 89: 3}

In [54]: C = {1: 3, 5:1}

In [55]: df.loc[(df['t1'].isin(A.keys()) & df['t2'].isin(B.keys()) & df['t3'].isin(C.keys()))]
Out[55]: 
   t1  t2  t3  t4  max_value
1  34  70   1   5         70

To answer @EdChum, I have assumed OP wants to check the presence of values in dictionary keys.

Upvotes: 2

Related Questions