[Pandas] 文本包含.str.contains()

.str.contains()会判断字符是否有包含关系,返回布尔序列,经常用在数据筛选中,它默认支持正则表达式,如果不需要,可以关掉

na参数可以指定空值的处理方式

import pandas as pd
import numpy as np
s = pd.Series(['One','Two','Three',np.NaN])
# 是否包含检测
res = s.str.contains('o',regex = False)

结果展示

s

res

用在数据查询中:

import pandas as pd

df = pd.DataFrame([['liver','E',89,21,24,64],
                   ['Arry','C',36,37,37,57],
                   ['Ack','A',57,60,18,84],
                   ['Eorge','C',93,96,71,78],
                   ['Oah','D',65,49,61,86]
                  ], 
                   columns = ['name','team','Q1','Q2','Q3','Q4'])

# 名字包含A字母
res1 = df.loc[df.name.str.contains('A')]
# 名字包含A字母或E字母
res2 = df.loc[df.name.str.contains('A|E')]
# 忽略大小写
import re
res3 = df.loc[df.name.str.contains('A|E', flags = re.IGNORECASE)]
# 包含数字
res4 = df.loc[df.name.str.contains('\d')]

结果展示

df

res1

res2

res3

res4

扩展 

.str.startswith()和.str.endswith()可以指定是开头还是结尾包含

import pandas as pd
import numpy as np
# 原数据
s = pd.Series(['One','Two','Three',np.NaN])
res1 = s.str.startswith('O')
# 对空值的处理
res2 = s.str.startswith('O',na = False)
res3 = s.str.endswith('e')
res4 = s.str.endswith('e',na = False)

结果展示

s

res1

res2

res3

res4

用.str.match()确定每个字符串是否与正则表达式匹配:

import pandas as pd
res = pd.Series(['1','2','3a','3b','03c']).str.match(r'[0-9][a-z]')

结果展示

  • 18
    点赞
  • 62
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值