在 pandas 中找到两个系列之间的交点 [英] Finding the intersection between two series in Pandas

查看:59
本文介绍了在 pandas 中找到两个系列之间的交点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在熊猫中有两个序列s1s2,并且想要计算交集,即该序列的所有值都是公共的.

I have two series s1 and s2 in pandas and want to compute the intersection i.e. where all of the values of the series are common.

我将如何使用concat函数执行此操作?我一直在尝试解决这个问题,但是却无法做到(我不想在s1s2的索引上计算交集,但在值上进行计算).

How would I use the concat function to do this? I have been trying to work it out but have been unable to (I don't want to compute the intersection on the indices of s1 and s2, but on the values).

推荐答案

将两个系列都放入Python的

Place both series in Python's set container then use the set intersection method:

s1.intersection(s2)

,然后根据需要转换回列表.

and then transform back to list if needed.

刚刚注意到标签中的熊猫.可以翻译成这样:

Just noticed pandas in the tag. Can translate back to that:

pd.Series(list(set(s1).intersection(set(s2))))

从注释中,我已将其更改为更具Pythonic的表达式,该表达式更短且更易于阅读:

From comments I have changed this to a more Pythonic expression, which is shorter and easier to read:

Series(list(set(s1) & set(s2)))

应该可以解决问题,除非索引数据对您也很重要.

should do the trick, except if the index data is also important to you.

已添加list(...)在转至pd.Series之前转换集,因为熊猫不接受集作为系列的直接输入.

Have added the list(...) to translate the set before going to pd.Series as pandas does not accept a set as direct input for a Series.

这篇关于在 pandas 中找到两个系列之间的交点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆