Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude one or more items from pandas Series

Tags:

python

pandas

I am wondering how to exclude one or more items from the pandas series. For example:

s = pd.Series(data=range(10), index=[chr(ord('A') + x) for x in range(10)])

Now I want to exclude rows B, D, E

An extremely inefficient way is to do this:

index = s.index
for col in ['B','D','E']:
    index = index.delete(index.get_loc(col))

new_series = s[index]

Is there any better way to do this?

Thanks.

like image 979
Tom Bennett Avatar asked Jul 09 '13 23:07

Tom Bennett


1 Answers

You could use the index isin method:

In [11]: s.index.isin(list('BDE'))
Out[11]: array([False,  True, False,  True,  True, False, False, False, False, False], dtype=bool)

negate using the invert operator (so it now reads "not in"):

In [12]: ~s.index.isin(list('BDE'))
Out[12]: array([ True, False,  True, False, False,  True,  True,  True,  True,  True], dtype=bool)

and use this to mask the Series:

In [13]: s = s[~s.index.isin(list('BDE'))]

In [14]: s
Out[14]:
A    0
C    2
F    5
G    6
H    7
I    8
J    9
dtype: int64
like image 172
Andy Hayden Avatar answered Sep 22 '22 15:09

Andy Hayden