2013-07-09 55 views
6

我想知道如何從熊貓系列中排除一個或多個項目。例如:從熊貓系列中排除一個或多個項目

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

現在我要排除的行B,d,E

一個非常低效的方法是做到這一點:

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

new_series = s[index] 

有沒有更好的方式來做到這一點?

謝謝。

回答

9

你可以使用索引isin法:用

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

否定反轉操​​作(所以它現在讀取「不」):

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

,並用它來掩蓋系列:

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