You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除温度数据中的摄氏度符号与括号?解决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)

处理后示例结果

清理转换后的数据会变为纯数值格式:

ParameterJanuaryFebruaryMarchAprilMayJuneJulyAugustSeptemberOctoberNovemberDecember
Avg. Temperature °C22.523.523.823.423.422.521.822.123.123.321.621.6
Avg. Temperature °F72.574.374.874.174.172.571.271.773.574.070.870.9

内容的提问来源于stack exchange,提问作者Bernard Ngoruse

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 12:25:42