我有两个不同长度的系列,我试图根据索引找到这两个系列的交集,其中索引是一个字符串。希望最终结果是一个具有基于公共(public)字符串索引的交集元素的系列。
有什么想法吗?
最佳答案
Pandas 索引有一个 intersection method你可以使用。如果你有两个系列,s1
和 s2
,那么
s1.index.intersection(s2.index)
或者,等价地:
s1.index & s2.index
为您提供 s1
和 s2
中的索引值。
然后您可以使用这个索引列表来查看系列的相应元素。例如:
>>> ixs = s1.index.intersection(s2.index)
>>> s1.loc[ixs]
# subset of s1 with only the indexes also found in s2 appears here
关于python - 使用索引在 Pandas 中查找两个系列之间的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26326489/