使用索引在Pandas中查找两个系列的交集

Bos*_*295 7 python intersection series pandas

我有两个不同长度的系列,我试图找到基于索引的两个系列的交集,其中索引是一个字符串.希望最终结果是一系列具有基于公共字符串索引的交集元素.

有任何想法吗?

Ale*_*ley 9

Pandas索引有一个可以使用的交集方法.如果你有两个系列,s1s2,然后

s1.index.intersection(s2.index)
Run Code Online (Sandbox Code Playgroud)

或者,等效地:

s1.index & s2.index
Run Code Online (Sandbox Code Playgroud)

给你这是在这两个指数值s1s2.

然后,您可以使用此索引列表来查看系列的相应元素.例如:

>>> ixs = s1.index.intersection(s2.index)
>>> s1.loc[ixs]
# subset of s1 with only the indexes also found in s2 appears here
Run Code Online (Sandbox Code Playgroud)

  • s1.index&s2.index做了类似的工作. (2认同)