python isin函数_pandas中isin()函数及其逆函数使用

本文介绍了Python pandas库中isin()函数的使用,包括如何通过布尔索引过滤DataFrame,以及isin()函数在数据清洗中的应用。此外,还展示了如何同时对多个列进行过滤,并提及了isin()的逆操作方法。
部署运行你感兴趣的模型镜像

pandas中isin()函数及其逆函数使用

发布时间:2018-05-27 21:11,

浏览次数:2021

, 标签:

pandas

isin

我使用这个函数就是用来清洗数据,删选过滤掉DataFrame中一些行。

布尔索引

这里你需要知道DateFrame中布尔索引这个东西,可以用满足布尔条件的列值来过滤数据,如下

>>> df=pd.DataFrame(np.random.randn(4,4),columns=['A','B','C','D']) >>> df A B

C D0 -0.018330 2.093506 -0.086293 -2.150479 1 0.104931 -0.271810 -0.054599

0.361612 2 0.590216 0.218049 0.157213 0.643540 3 -0.254449 -0.593278 -0.150455 -

0.244485 >>> df.A>0#布尔索引 0 False 1 True 2 True 3 False Name: A, dtype: bool

#布尔索引应用 >>> df[df.A>0] A B C D 1 0.104931 -0.271810 -0.054599 0.361612 2

0.590216 0.218049 0.157213 0.643540 >>>

isin()

添加一列E

>>> df['E']=['a','a','c','b'] >>> df A B C D E 0 -0.018330 2.093506 -0.086293 -

2.150479 a 1 0.104931 -0.271810 -0.054599 0.361612 a 2 0.590216 0.218049

0.157213 0.643540 c 3 -0.254449 -0.593278 -0.150455 -0.244485 b >>> df.E.isin([

'a','c']) 0 True 1 True 2 True 3 False Name: E, dtype: bool >>> df.isin(['b','c'

])#整个df也同样适用 A BC D E 0 False False False False False 1 False False False False

False 2 False False False False True 3 False False False False True #应用 >>>

df[df.E.isin(['a','c'])] A B C D E 0 -0.018330 2.093506 -0.086293 -2.150479 a 1

0.104931 -0.271810 -0.054599 0.361612 a 2 0.590216 0.218049 0.157213 0.643540 c

>>>

isin()接受一个列表,判断该列中元素是否在列表中。

同时对多个列过滤,可以如下使用

df[df[某列].isin(条件)&df[某列].isin(条件)] #应用 >>> df.D=[0,1,0,2] >>> df[df.E.isin([

'a','d'])&df.D.isin([0,])] A B C D E 0 -0.01833 2.093506 -0.086293 0 a

也可以

不推荐,你试一下就知道

df.isin({ '某列':[条件], '某列':[条件], }) #应用 >>> df.D=[0,1,0,2] >>> df A B C D E 0 -

0.018330 2.093506 -0.086293 0 a 1 0.104931 -0.271810 -0.054599 1 a 2 0.590216

0.218049 0.157213 0 c 3 -0.254449 -0.593278 -0.150455 2 b >>> df[df.isin({'D':[0

,3],'E':['a','d']})] A B C D E 0 NaN NaN NaN 0.0 a 1 NaN NaN NaN NaN a 2 NaN

NaN NaN0.0 NaN 3 NaN NaN NaN NaN NaN #没错这不适合选出一行 >>> df.isin({'D':[0,3],'E':['a'

,'d']}) A B C D E 0 False False False True True 1 False False False False True 2

False False False True False 3 False False False False False

isin()的逆函数

告诉你没有isnotin,它的反函数就是在前面加上 ~ ,其他用法同上。

您可能感兴趣的与本文相关的镜像

Stable-Diffusion-3.5

Stable-Diffusion-3.5

图片生成
Stable-Diffusion

Stable Diffusion 3.5 (SD 3.5) 是由 Stability AI 推出的新一代文本到图像生成模型,相比 3.0 版本,它提升了图像质量、运行速度和硬件效率

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值