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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With