python中isin函数_pandas中的isin函数详解

本文详细介绍了如何使用 Pandas 中的 isin 函数来实现 SQL 的 not in 逻辑,包括对 DataFrame、序列和数组的元素进行成员资格检查,并通过示例展示了如何将 isin 结合取反操作实现 not in 功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天有个同学问到,not in 的逻辑,想用 SQL 的select c_xxx_s from t1 left join t2 on t1.key=t2.key where t2.key is NULL 在 Python 中的逻辑来实现,实现了 left join 了(直接用join方法),但是不知道怎么实现where key is NULL。

其实,实现not in的逻辑,不用那么复杂,直接用isin函数再取反即可,下面就是isin函数的详解。

import pandas;

df = pandas.DataFrame({

'A': [1, 2, 3],

'B': ['a', 'b', 'f']

})

#如果是一个序列或者数组,

#那么判断该位置的值,是否在整个序列或者数组中

df.isin(

[1, 3, 12, 'a']

)

A      B

0   True   True

1  False  False

2   True  False

df = pandas.DataFrame({

'A': [1, 2, 3],

'B': [1, 4, 7]

})

#如果是一个dirt,

#那么就会首先判断对应的index是否存在,

#如果存在,那么就会判断对应的位置,在该列是否存在

df.isin({

'A': [1, 3],

'B': [4, 7, 12]

})

A      B

0   True  False

1  False   True

2   True   True

#如果不存在,那么全部为False,例如B列没有,那么全部为False

df.isin({

'A': [1, 3],

'C': [4, 7, 12]

})

A      B

0   True  False

1  False  False

2   True  False

df = pandas.DataFrame({

'A': [1, 2, 3],

'B': ['a', 'b', 'f']

})

other = pandas.DataFrame({

'A': [1, 3, 3, 2],

'B': ['e', 'f', 'f', 'e']

})

#如果是一个DataFrame,

#首先就是列名要存在,

#并且需要df中行列位置和B对应的行列位置一一匹配,才返回TRUE

df.isin(other)

A      B

0   True  False

1  False  False

2   True   True

other = pandas.DataFrame({

'C': [1, 3, 3, 2],

'D': ['e', 'f', 'f', 'e']

})

#因为AB列皆不在,因此都为False

df.isin(other)

A      B

0  False  False

1  False  False

2  False  False

嗯嗯?还没有讲到not in?哦哦,没有isnotin函数,取反的方法就是在函数前面加个 ~ ,好销魂的一飘。

~df.isin(other)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值