Tom Bennett
Tom Bennett

Reputation: 2506

Exclude one or more items from pandas Series

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.

Upvotes: 9

Views: 7502

Answers (1)

Andy Hayden
Andy Hayden

Reputation: 375925

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

Upvotes: 14

Related Questions