pandas 利用 正则表达式 从文本中提取数字

需要从text特征中提取形如 13.5/10 这样的字符串,再分别提取分子分母。
1)可以利用 str.extract() 方法。
2)利用正则表达式 \d+\.?\d*\/\d+ 进行匹配
3)再利用 .split() 方法提取分子分母

代码:
这里写图片描述

test.text.tolist()

# output
['This is Bella. She hopes her smile made you smile. If not, she is also offering you her favorite monkey. 13.5/10 https://t.co/qjrljjt948',
 "This is Logan, the Chow who lived. He solemnly swears he's up to lots of good. H*ckin magical af 9.75/10 https://t.co/yBO5wuqaPS",
 "This is Sophie. She's a Jubilant Bush Pupper. Super h*ckin rare. Appears at random just to smile at the locals. 11.27/10 would smile back https://t.co/QFaUiIHxHq",
 'Here we have uncovered an entire battalion of holiday puppers. Average of 11.26/10 https://t.co/eNm2S6p9BD']
test['rating'] = test['text'].str.extract(r'(\d+\.?\d*\/\d+)', expand=False)

# 提取分子
test['rating_numerator'] = test.rating.apply(lambda x: eval(x.split('/')[0]))
# 提取分母
test['rating_denominator_fix'] = test.rating.apply(lambda x: eval(x.split('/')[1]))
# 删除中间量
test.drop(['rating'], axis=1, inplace=True)

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值