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

机器学习降雨量预测项目报错:ValueError无法将空串转为浮点数

解决LinearRegression训练时的字符串转浮点错误及Series转换问题

问题根源

  1. 你的Excel数据中存在空字符串('')这类非数值型数据,无法被LinearRegression模型处理,触发ValueError: could not convert string to float: ''。
  2. 直接用float(x)转换整个Series无效,因为float()仅能处理单个数值,而Series是一组数据的集合。
  3. LinearRegression.fit()要求特征数据为二维数组(形状为(n_samples, n_features)),但你提取的x是一维Series,这也是潜在的报错点。

解决方案及修改后代码

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import metrics

# 读取指定列数据
df = pd.read_excel('Month.xlsx', usecols='W, AJ')

# 重命名列(可选,方便后续识别操作)
df.columns = ['Luchtvochtigheid', 'Regenval']

# 1. 转换数据类型:将空字符串、非数值值转为NaN,再统一转浮点型
df['Luchtvochtigheid'] = pd.to_numeric(df['Luchtvochtigheid'], errors='coerce')
df['Regenval'] = pd.to_numeric(df['Regenval'], errors='coerce')

# 2. 处理缺失值:删除含NaN的行(或用均值/中位数填充,示例用删除)
# 若要填充可替换为:df.fillna(df.mean(), inplace=True)
df = df.dropna(subset=['Luchtvochtigheid', 'Regenval'])

# 3. 调整特征数据形状:将一维Series转为二维数组,满足模型输入要求
x = df['Luchtvochtigheid'].values.reshape(-1, 1)
y = df['Regenval'].values

# 4. 拆分训练集与测试集(可选但推荐,避免过拟合)
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)

# 训练模型
model = LinearRegression()
model.fit(x_train, y_train)

# 预测及可视化
y_pred = model.predict(x_test)
plt.scatter(x_test, y_test, color='gray')
plt.plot(x_test, y_pred, color='red', linewidth=2)
plt.xlabel('Luchtvochtigheid')
plt.ylabel('Regenval')
plt.show()

# 可选:打印模型评估指标
print(f'Mean Absolute Error: {metrics.mean_absolute_error(y_test, y_pred)}')
print(f'Mean Squared Error: {metrics.mean_squared_error(y_test, y_pred)}')

关键步骤说明

  • pd.to_numeric(..., errors='coerce'):自动将空字符串、非数值内容转为NaN,避免转换失败报错。
  • dropna()/fillna():清理缺失值,确保模型训练仅使用有效数据;填充法更适合数据量较小的场景。
  • reshape(-1,1):将一维特征数组转为(样本数, 1)的二维结构,完全匹配LinearRegression的输入格式要求。

内容的提问来源于stack exchange,提问作者kemal ozdogan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 09:32:33