如何移除温度数据中的摄氏度符号与括号?解决astype(float)转换报错
解决方案
针对你的温度数据,可通过字符串提取/替换清理非数字内容后转浮点型,具体代码如下:
方法1:提取数字部分(推荐,适配所有带符号/括号的情况)
使用str.extract直接提取字符串中的整数或小数,自动忽略括号、°C/°F等无关字符:
import pandas as pd # 假设数据已存入DataFrame df # 对所有列执行数字提取操作 df = df.apply(lambda col: col.str.extract(r'(\d+\.?\d*)', expand=False)) # 转换为浮点型 df = df.astype(float)
正则表达式(\d+\.?\d*)会精准匹配所有整数和小数格式的数值,无需逐个清理符号。
方法2:逐个替换无关字符
如果需要针对性清理特定符号,可分步替换掉括号、°C、°F:
# 替换括号为空 df = df.replace(r'[\(\)]', '', regex=True) # 替换°和单位标识为空 df = df.replace(r'°[CF]', '', regex=True) # 转换为浮点型 df = df.astype(float)
处理后示例结果
清理转换后的数据会变为纯数值格式:
| Parameter | January | February | March | April | May | June | July | August | September | October | November | December |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Avg. Temperature °C | 22.5 | 23.5 | 23.8 | 23.4 | 23.4 | 22.5 | 21.8 | 22.1 | 23.1 | 23.3 | 21.6 | 21.6 |
| Avg. Temperature °F | 72.5 | 74.3 | 74.8 | 74.1 | 74.1 | 72.5 | 71.2 | 71.7 | 73.5 | 74.0 | 70.8 | 70.9 |
内容的提问来源于stack exchange,提问作者Bernard Ngoruse
相关产品推荐
相关产品推荐

