无需正则表达式的Pandas复杂字符串处理方法咨询
不用正则表达式转换长度字符串为英寸数值
核心思路
通过字符串分割、关键词匹配和类型转换,逐个解析英尺(ft)和英寸(in)部分,最终累加得到总英寸数,全程无需正则表达式。
步骤1:定义转换函数
这个函数能处理多种输入格式,包括同时含英尺和英寸、仅含单一单位、纯数字(默认按英寸处理)的情况,还能兼容大小写和多余空格:
import pandas as pd import numpy as np def convert_to_inches(s): # 处理空值或非字符串输入 if pd.isna(s): return np.nan # 统一转小写、去除首尾空格,消除格式干扰 s = str(s).lower().strip() total_inches = 0.0 # 解析英尺部分(ft) if 'ft' in s: ft_part, remaining = s.split('ft', 1) try: # 提取数字并转换为英尺,再转成英寸 ft_value = float(ft_part.strip()) total_inches += ft_value * 12 except ValueError: # 数字格式错误时跳过该部分 pass # 保留剩余字符串用于解析英寸 s = remaining.strip() # 解析英寸部分(in) if 'in' in s: in_part, _ = s.split('in', 1) try: inch_value = float(in_part.strip()) total_inches += inch_value except ValueError: pass # 处理纯数字输入(默认视为英寸) if not total_inches and s.replace('.', '', 1).isdigit(): try: total_inches = float(s) except ValueError: pass # 无有效数值时返回NaN return total_inches if total_inches != 0 else np.nan
步骤2:应用到Pandas列
假设你的目标列名为length,直接用apply方法批量处理:
# 替换成你的DataFrame和列名 df['length_inches'] = df['length'].apply(convert_to_inches)
测试示例
| 输入字符串 | 输出英寸值 |
|---|---|
| "9ft 2in" | 110.0 |
| "5ft" | 60.0 |
| "3in" | 3.0 |
| "10.5ft" | 126.0 |
| "7.2in" | 7.2 |
| "123" | 123.0 |
| "abc" | NaN |
扩展优化(可选)
如果需要支持foot/feet、inch/inches这类完整单位词,只需在判断条件中添加对应关键词即可,比如:
# 替换英尺判断逻辑 if any(unit in s for unit in ['ft', 'foot', 'feet']): # 按第一个匹配的单位拆分 for unit in ['ft', 'foot', 'feet']: if unit in s: ft_part, remaining = s.split(unit, 1) break # 后续处理逻辑不变
内容的提问来源于stack exchange,提问作者Favour Onyido
相关产品推荐
相关产品推荐

