Python 从熊猫系列中排除一个或多个项目
我想知道如何从熊猫系列中排除一个或多个项目。例如:Python 从熊猫系列中排除一个或多个项目,python,pandas,Python,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] 有没有更好的办法 谢谢
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]
有没有更好的办法
谢谢 您可以使用索引方法:
使用反转运算符求反(因此现在显示为“不在”):
并使用此选项遮罩系列:
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
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