Exclude one or more items from the pandas series

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

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

Now I want to exclude lines B, D, E

An extremely inefficient way is to:

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

Is there a better way to do this?

Thanks.

+6
source share
1 answer

You can use the isin index method:

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

deny using the inverting operator (so now it 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 
+9
source

Source: https://habr.com/ru/post/949065/


All Articles