本文介绍了Pandas数据查找常用函数,掌握了这些函数的应用,让你在数据处理时,手到擒来,游刃有余。
目录
一、查找数据位置 s.str.find()和s.str.index()函数
二、数据的查找判断
1. 判断开头或结尾是否是指定字符串s.startswith()和s.str.endswith()
2.判断是否包含指定字符串 s.str.contains()
3. 判断是否从开头查找s.str.match()
三、数据查找s.str.findall()
1. 提取查找成功的字符串s.str.findall()
总结
一、查找数据位置 s.str.find()和s.str.index()函数
函数详解:
s.str.find(sub start end )
s.str.index(sub start end)
| sub | 要查找的字符串 |
| start | 字符串开始的位置 |
| end | 字符串结束的位置 |
import pandas as pd
s=pd.Series(['张三45李四5458','GFJL黄大发56大商股份54','Bob545fah55g6fg45'])
s.str.find('5')
s.str.index('5')
查找函数s.str.find(sub start end )和s.str.index(sub start end)均返回字符串的索引;
如果查不到s.str.find()的返回值为-1;s.str.index()报错:ValueError: substring not found;
二、数据的查找判断s.str.startswith()和s.str.endswith()
1. 判断开头或结尾是否是指定字符串s.startswith()和s.str.endswith()
函数详解:
s.str.startswith(pat,na=None) 判定字符串开头是
s.str.endswith(pat,na=None) 判定字符串结尾是
pat 要查找的字符串,支持正则表达式
na 对缺失值的处理
s=pd.Series(['12fdf','asf54','asfg456','asf45as',' 54 saf'])
s.str.startswith('1') #查找1开头的字符串
s.str.endswith('6') #查找以6结尾的字符串
s.str.startswith()函数查找字符串开始的值,返回值为逻辑值,True或False;
s.str.endswith()函数查找字符串结束的值,返回值为逻辑值,True或False;
2.判断是否包含指定字符串 s.str.contains()
函数详解:
s.str.contains(pat,case=True,flags=0,na=None,regex=True)
| pat | 字符串或正则表达式字符串 |
| case | 区分大小写,True区分,False不区分 |
| flags | re模块中的标志 |
| na | 缺失值的处理 |
| regex | 是否将pat视为正则表达式 |
s=pd.Series(['12fdf','asf54','5asfg456','asf45as',' 54 saf'])
s.str.contains('^d+') #查找数字开头的字符串
s.str.contains()函数判断是否包含指定字符串,返回值的bool,支持正则表达式;
3. 判断是否从开头查找s.str.match()
函数详解:
s.str.match(pat,case=True,flags=0,na)
| pat | 字符串或正则表达式字符串 |
| case | 区分大小写,True区分,False不区分 |
| flags | re模块中的标志 |
| na | 缺失值的处理 |
s=pd.Series(['12fdf','asf54','5asfg456','asf45as',' 54 saf'])
s.str.match('d.+d') #查找数字开头,数字结尾的字符串
s.str.match()相当于s.str.startswith(),两者略有区别;
区别:
s.str.match()支持正则表达式;s.str.startswith()不支持正则表达式;
三、数据查找s.str.findall()
1. 提取查找成功的字符串s.str.findall()
import re
import pandas as od
s=pd.Series(['ajf4d8g5s7hasktg45gd','jafig65a4gfhiaf4af','ashf54a8g5a'])
s.str.findall('d+') #查找字符串中的数字
import re
import pandas as od
s=pd.Series(['ajf4d8g5s7hasktg45gd','jafig65a4gfhiaf4af','ashf54a8g5a'])
s.str.findall('d+') #查找字符串中的数字
总结
| 函数 | 作用 | 是否支持正则 |
| s.str.find() | 查找位置 | 否 |
| s.str.index() | 查找位置 | 否 |
| s.str.startswith() | 查找判断 | 否 |
| s.str.endswith() | 查找判断 | 否 |
| s.str.contains() | 查找判断 | 是 |
| s.str.match() | 查找判断 | 是 |
| s.str.findall() | 查找数据 | 是 |



