Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filtering a Pandas DataFrame using dictionary

Tags:

python

pandas

I have a Pandas dataframe with multiple columns and I would like to filter it to get a subset that matches certain values in different columns. I used the isin() method and passed a dictionary but I keep getting the TypeError with the message TypeError: only list-like or dict-like objects are allowed to be passed to DataFrame.isin(), you passed a 'str'.

Following is an example of the problem:

x = pd.DataFrame({'surname':['wang','park','park'],'name':['tim','john','sam']})
display(x)

filt_dict = {'surname':'park'}

x[x.isin(filt_dict)]

I expected two rows where the surname matches park, but I get the TypeError instead.

What gives?

like image 384
bluetooth Avatar asked Oct 17 '19 16:10

bluetooth


2 Answers

As you need to filter by dict values:

In [118]: x[x.surname.isin(filt_dict.values())]
Out[118]: 
  surname  name
1    park  john
2    park   sam
like image 180
RomanPerekhrest Avatar answered Oct 16 '22 11:10

RomanPerekhrest


The values of the filtering dict must be lists:

x = pd.DataFrame({'surname': ['wang', 'park', 'park'], 'name': ['tim', 'john', 'sam']})

d = {'surname': ['park']}

print(x.isin(d))

Output

   surname   name
0    False  False
1     True  False
2     True  False
like image 32
Dani Mesejo Avatar answered Oct 16 '22 12:10

Dani Mesejo