从pandas系列中排除一个或多个项目

9
我想知道如何从pandas系列中排除一个或多个项目。例如:
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]

有没有更好的方式来做这件事呢?谢谢。
1个回答

14
你可以使用索引isin方法:
In [11]: s.index.isin(list('BDE'))
Out[11]: array([False,  True, False,  True,  True, False, False, False, False, False], dtype=bool)
使用反转运算符进行否定(使其变为“not in”):
In [12]: ~s.index.isin(list('BDE'))
Out[12]: array([ True, False,  True, False, False,  True,  True,  True,  True,  True], dtype=bool)

使用此方法来对 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接