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

Pandas DataFrame字符串转float报错:无法转换空字符串

解决Pandas中rain_1h列转float时的空字符串错误

你的代码执行后,rain_1h列中存在空字符串(''),这类值无法直接转为float类型,因此触发ValueError。以下是具体解决方法:

方案1:将空字符串转为NaN(适合后续缺失值处理)

合并替换操作减少重复调用,先清理字符串,再把空值转为NaN后转类型:

# 一次性完成所有替换操作
df_tmp['rain_1h'] = df_tmp['rain_1h'].replace({'zero': '0', 'mm': '', ' ': ''}, regex=True)
# 去除首尾空白,将空字符串转为NaN,再转为float类型
df_tmp['rain_1h'] = df_tmp['rain_1h'].str.strip().replace('', float('nan')).astype(float)

方案2:将空字符串转为0(适合业务上空值代表无降雨)

如果业务逻辑中空值意味着没有降雨,可直接替换为0:

df_tmp['rain_1h'] = df_tmp['rain_1h'].replace({'zero': '0', 'mm': '', ' ': ''}, regex=True)
# 去除首尾空白,空字符串替换为'0'后转float
df_tmp['rain_1h'] = df_tmp['rain_1h'].str.strip().replace('', '0').astype(float)

额外排查步骤

如果仍有报错,可先打印列中所有唯一值,排查是否存在其他异常字符串:

print(df_tmp['rain_1h'].unique())

内容的提问来源于stack exchange,提问作者Andi Muhammad Alif Alfajra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 23:35:05