Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find rows in dataframe with dict

Tags:

pandas

df = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6]}) 

produces

   a  b
0  1  4
1  2  5
2  3  6

Given a dict

d = {'a': 2, 'b': 5}

how would I extract the rows of the dataframe where the dict's keys values match all the column values -- so in this case

   a  b
1  2  5
like image 557
Hatshepsut Avatar asked Jan 28 '19 22:01

Hatshepsut


2 Answers

You can compare with Series and filter:

df[(df == pd.Series(d)).all(1)]

   a  b
1  2  5

This comparison is aligned on the index/columns and broadcasted for each row.

like image 195
cs95 Avatar answered Oct 04 '22 23:10

cs95


Compare the values and use indexing,

df[ (df.values == np.array(list(d.values()))).all(1) ]

    a   b
1   2   5
like image 36
Vaishali Avatar answered Oct 05 '22 00:10

Vaishali