Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter Pandas Data Frame based on exact string match

I want to filter a pandas data frame based on exact match of a string.

I have a data frame as below

df1 = pd.DataFrame({'vals': [1, 2, 3, 4,5], 'ids': [u'aball', u'bball', u'cnut', u'fball','aballl']})    

I want to filter all the rows except the row that has 'aball'.As you can see I have one more entry with ids == 'aballl'. I want that filterd out. Hence the below code does not work:

df1[df1['ids'].str.contains("aball")]    

even str.match does not work

df1[df1['ids'].str.match("aball")] 

Any help would be greatly appreciated.

like image 282
Abhijith N Avatar asked Jul 18 '17 10:07

Abhijith N


2 Answers

Keeping it simple, this should work:

df1[df1['ids'] == "aball"] 
like image 99
IanS Avatar answered Nov 03 '22 13:11

IanS


You can try this:

df1[~(df1['ids'] == "aball")] 

Essentially it will find all entries matching "aball" and then negate it.

like image 23
Nick M Avatar answered Nov 03 '22 14:11

Nick M