pandas的数据筛选之isin和str.contains函数
筛选是在平时的工作中使用非常频繁的功能,前文介绍了loc和iloc的筛选方法,现在继续介绍一些筛选的方法。
![](http://upload-images.jianshu.io/upload_images/8612260-cc0bfd1e33b3a1a7.png)
DataFrame列表
以>,<,==,>=,<=来进行选择(“等于”一定是用‘==’,如果用‘=’就不是判断大小了):
![](http://upload-images.jianshu.io/upload_images/8612260-1c73393e971809ab.png)
选择quantity>25的所有行
![](http://upload-images.jianshu.io/upload_images/8612260-3158f8e1b4e1ec62.png)
选择数量大于20或单价大于100的所有行
使用 &(且) 和 |(或) 时每个条件都要用小括号括起来。
选取多列一定是两个方括号,其中内侧方括号代表是一个list:
![](http://upload-images.jianshu.io/upload_images/8612260-71086ec8bbf1f977.png)
使用一般方式
![](http://upload-images.jianshu.io/upload_images/8612260-15221779c8d0eaa2.png)
使用loc函数
如果要选择某列等于多个数值或者字符串时,要用到.isin(), 我们把df修改了一下(isin()括号里面应该是个list):
![](http://upload-images.jianshu.io/upload_images/8612260-a28d4eccfe2d78e4.png)
使用isin函数筛选
![](http://upload-images.jianshu.io/upload_images/8612260-494017623f7290b9.png)
使用loc函数筛选
平时使用最多的筛选应该是字符串的模糊筛选,在SQL语句里用的是like,在pandas里我们可以用.str.contains()来实现。
![](http://upload-images.jianshu.io/upload_images/8612260-b6b789cfa3da290a.png)
使用str.contains函数筛选
![](http://upload-images.jianshu.io/upload_images/8612260-60e7a490a45d80ff.png)
直接使用loc函数筛选
也可以使用 '|' 来进行多个条件的筛选:
![](http://upload-images.jianshu.io/upload_images/8612260-0c07d4d0364858d9.png)
筛选包含某一字符的行
![](http://upload-images.jianshu.io/upload_images/8612260-c6f4fd6f607886fb.png)
筛选包含某一字符的行
![](http://upload-images.jianshu.io/upload_images/8612260-992f22f786ee221f.png)
多条件筛选
注意,这个‘|’是在引号内的,而不是将两个字符串分别引起来。’&‘在这里不能用。
如果中间的.str不用的话,就会出错,提示‘Series’数组没有‘contains'函数。
![](http://upload-images.jianshu.io/upload_images/8612260-4af8e23b89c4ab2c.png)
str函数的作用
其实.str的作用就是将’Series‘转换为类似Strings的结构,然后就可以用contains函数了。
作者:探索数据之美
链接:https://www.jianshu.com/p/805f20ac6e06
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步