Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter strings in pandas series index

I'm trying to filter a pandas series by using a boolean expression on its index, which contains strings. For example, in the code below I wish to create a new Series (Sman) by filtering another series (S) for rows where the index items contain the substring 'man':

from pandas import Series
S = Series({'moondog':12,'catman':23, 'batman':31, 'catdog':42})
Sman = S['man' in S]

However, the result for Sman is simply the number 31, and not a new series containing the rows for 'catman' and 'batman' as I was hoping for.

What am I doing wrong??

like image 975
dreme Avatar asked Aug 10 '14 11:08

dreme


1 Answers

You can use the filter method:

In [11]: S.filter(like='man')
Out[11]:
batman    31
catman    23
dtype: int64

A manual alternative would be:

In [12]: S[['man' in i for i in S.index]]
Out[12]:
batman    31
catman    23
dtype: int64

The reason your approach did not work is that 'man' in S just returns False, as this checks if the exact label 'man' is contained in the index (which is not the case).

like image 152
joris Avatar answered Oct 23 '22 11:10

joris