如何移除DataFrame列中除小数点外的文本与字符?
处理Pandas DataFrame中Weight列的无关文本,提取有效数值
问题描述
Pandas DataFrame的weight列从CSV导入后包含大量无关文本,需要移除所有字母及小数点(.)、正负号(+/-)之外的字符,最终将该列转换为数值类型。
示例数据
import pandas as pd df = pd.DataFrame( [ (1, '+9.1A', 100), (2, '-1A', 121), (3, '5B', 312), (4, '+1D', 567), (5, '+1C', 123), (6, '-2E', 101), (7, '+3T', 231), (8, '5A', 769), (9, '+5B', 907), (10, 'text', 15), ], columns=['colA', 'weight', 'colC'] )
解决方案
方法1:正则替换移除无关字符
通过正则表达式过滤掉非数值相关的字符,再转换为数值类型:
# 1. 将列转为字符串,确保统一处理 df['weight_clean'] = df['weight'].astype(str) # 2. 移除所有非数字、非小数点、非正负号的字符 df['weight_clean'] = df['weight_clean'].str.replace(r'[^0-9\.\-\+]', '', regex=True) # 3. 转换为数值,无法转换的内容转为NaN df['weight_clean'] = pd.to_numeric(df['weight_clean'], errors='coerce') # 查看结果 print(df)
方法2:正则提取有效数值片段
如果文本中可能夹杂多个数字片段,可精准提取符合数值格式的内容:
# 提取开头的正负号(可选)+ 数字 + 可选小数点 + 可选小数位 df['weight_clean'] = df['weight'].astype(str).str.extract(r'([-+]?\d+\.?\d*)', expand=False) # 转换为数值,无效内容转为NaN df['weight_clean'] = pd.to_numeric(df['weight_clean'], errors='coerce') print(df)
真实场景适配
针对包含缺失值、纯文本的真实数据,两种方法都能有效处理:
df = pd.DataFrame( [ (0,68), (1,67), (2,68.1), (3,97.1), (4,113.9), (5,114), (6,112), (7,111.8), (8,111), (9,110.8), (10,111.2), (11,), (12,111.5), (13,'Not Appropriate at t'), ], columns=['colA', 'weight'] ) # 套用方法1或方法2即可 df['weight_clean'] = df['weight'].astype(str).str.replace(r'[^0-9\.\-\+]', '', regex=True) df['weight_clean'] = pd.to_numeric(df['weight_clean'], errors='coerce') print(df)
说明
astype(str):确保所有值统一为字符串类型,避免非字符串值处理报错pd.to_numeric(..., errors='coerce'):将处理后的字符串转为数值,无法转换的内容(如纯文本、空字符串)会被转为NaN,方便后续缺失值处理
内容的提问来源于stack exchange,提问作者Natali
相关产品推荐
相关产品推荐

