如何删除DataFrame中Score列的括号与Score:前缀?
清理Pandas DataFrame中Score列的文本格式
针对你的需求,这里提供几种高效的方法来去除Score列中的括号和Score:文本,提取出纯数值:
方法1:正则表达式提取数字(推荐)
利用str.extract直接提取浮点数部分,适配性更强,即使文本格式有小变动也能生效:
import pandas as pd df1 = pd.DataFrame({'Parent': ['Stay home', "Stay home","Stay home", 'Go outside'], 'Child' : ['Severe weather', "Severe weather", "Severe weather", 'Sunny'], 'Score': ['(Score: 0.0310)', '(Score: 0.0310)', '(Score: 0.0310)', '(Score: 0.0310)']}) # 提取浮点数并转换为数值类型 df1['Score'] = df1['Score'].str.extract(r'(\d+\.\d+)', expand=False).astype(float) print(df1)
输出结果:
Parent Child Score 0 Stay home Severe weather 0.0310 1 Stay home Severe weather 0.0310 2 Stay home Severe weather 0.0310 3 Go outside Sunny 0.0310
方法2:分步字符串替换
通过两次替换操作,先去除括号,再移除Score:标识:
# 移除括号和Score:文本 df1['Score'] = df1['Score'].str.replace(r'[()]', '', regex=True).str.replace('Score: ', '') # 转换为数值类型(可选) df1['Score'] = df1['Score'].astype(float)
方法3:字符串拆分截取
利用固定格式的特点,按冒号拆分后截取目标部分:
# 拆分字符串后提取数字部分 df1['Score'] = df1['Score'].str.split(':').str[1].str.strip().str.rstrip(')').astype(float)
补充说明
如果后续需要对Score列进行数值计算,务必加上.astype(float)将字符串转换为浮点型;若仅需保留字符串格式,可省略该步骤。
内容的提问来源于stack exchange,提问作者xavi
相关产品推荐
相关产品推荐

