pandas的数据筛选之isin和str.contains函数
筛选是在平时的工作中使用非常频繁的功能,前文介绍了loc和iloc的筛选方法,现在继续介绍一些筛选的方法。
![](http://upload-images.jianshu.io/upload_images/8612260-cc0bfd1e33b3a1a7.png?imageMogr2/auto-orient/strip|imageView2/2/w/752/format/webp)
DataFrame列表
以>,<,==,>=,<=来进行选择(“等于”一定是用‘==’,如果用‘=’就不是判断大小了):
![](http://upload-images.jianshu.io/upload_images/8612260-1c73393e971809ab.png?imageMogr2/auto-orient/strip|imageView2/2/w/758/format/webp)
选择quantity>25的所有行
![](http://upload-images.jianshu.io/upload_images/8612260-3158f8e1b4e1ec62.png?imageMogr2/auto-orient/strip|imageView2/2/w/746/format/webp)
选择数量大于20或单价大于100的所有行
使用 &(且) 和 |(或) 时每个条件都要用小括号括起来。
选取多列一定是两个方括号,其中内侧方括号代表是一个list:
![](http://upload-images.jianshu.io/upload_images/8612260-71086ec8bbf1f977.png?imageMogr2/auto-orient/strip|imageView2/2/w/748/format/webp)
使用一般方式
![](http://upload-images.jianshu.io/upload_images/8612260-15221779c8d0eaa2.png?imageMogr2/auto-orient/strip|imageView2/2/w/743/format/webp)
使用loc函数
如果要选择某列等于多个数值或者字符串时,要用到.isin(), 我们把df修改了一下(isin()括号里面应该是个list):
![](http://upload-images.jianshu.io/upload_images/8612260-a28d4eccfe2d78e4.png?imageMogr2/auto-orient/strip|imageView2/2/w/746/format/webp)
使用isin函数筛选
![](http://upload-images.jianshu.io/upload_images/8612260-494017623f7290b9.png?imageMogr2/auto-orient/strip|imageView2/2/w/745/format/webp)
使用loc函数筛选
平时使用最多的筛选应该是字符串的模糊筛选,在SQL语句里用的是like,在pandas里我们可以用.str.contains()来实现。
![](http://upload-images.jianshu.io/upload_images/8612260-b6b789cfa3da290a.png?imageMogr2/auto-orient/strip|imageView2/2/w/745/format/webp)
使用str.contains函数筛选
![](http://upload-images.jianshu.io/upload_images/8612260-60e7a490a45d80ff.png?imageMogr2/auto-orient/strip|imageView2/2/w/744/format/webp)
直接使用loc函数筛选
也可以使用 '|' 来进行多个条件的筛选:
![](http://upload-images.jianshu.io/upload_images/8612260-0c07d4d0364858d9.png?imageMogr2/auto-orient/strip|imageView2/2/w/737/format/webp)
筛选包含某一字符的行
![](http://upload-images.jianshu.io/upload_images/8612260-c6f4fd6f607886fb.png?imageMogr2/auto-orient/strip|imageView2/2/w/745/format/webp)
筛选包含某一字符的行
![](http://upload-images.jianshu.io/upload_images/8612260-992f22f786ee221f.png?imageMogr2/auto-orient/strip|imageView2/2/w/777/format/webp)
多条件筛选
注意,这个‘|’是在引号内的,而不是将两个字符串分别引起来。’&‘在这里不能用。
如果中间的.str不用的话,就会出错,提示‘Series’数组没有‘contains'函数。
![](http://upload-images.jianshu.io/upload_images/8612260-4af8e23b89c4ab2c.png?imageMogr2/auto-orient/strip|imageView2/2/w/725/format/webp)
str函数的作用
其实.str的作用就是将’Series‘转换为类似Strings的结构,然后就可以用contains函数了。
作者:探索数据之美
链接:https://www.jianshu.com/p/805f20ac6e06