如何删除索引标签不在列表中的 rows/items of pandas 系列?

How can I delete rows/items of pandas series with indices' labels not in a list?

我有一个标签列表。

我还有一个 pandas 系列,其中有多个 rows/items,其中一些在该列表中有索引标签,而另一些索引标签不在该列表中。

我想删除标签不在该列表中的该系列的 rows/items。

我能想到的唯一方法是迭代系列,检查索引标签是否在该列表中,如果不在则将其删除。

还有其他更简单的方法吗?如果没有,有人可以提供这样的代码,因为我也无法让它工作(不确定如何迭代系列以及如何将其索引标签与列表中的标签进行比较)。

非常感谢您的帮助。

您可以使用 Index.intersection with loc:

s = pd.Series([1,2,5,6], index=list('abcd'))
print (s)
a    1
b    2
c    5
d    6
dtype: int64

L = list('cdef')
print (s.loc[s.index.intersection(L)])
c    5
d    6
dtype: int64

另一种可能的解决方案isin

print (s.loc[s.index.isin(L)])
c    5
d    6
dtype: int64