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

数据清洗处理数值列时遇ValueError形状不匹配问题求助

解决ValueError: shape mismatch的问题

这个错误的根源很明确:你试图用apply处理DataFrame的多列数据,但apply是按行或列(Series级别)来操作的,而你实际需要的是逐个处理每个单元格的内容,这就导致了形状不匹配的问题。

让我们拆解代码里的问题:

  • weather_list[numeric_cols].apply(lambda x: re.sub('[^0-9]', '', str(x))):当对多列DataFrame调用apply时,默认按列(axis=0)处理,此时x代表一整列的Series数据。你把整个Series转成字符串(比如类似"0 12.3\n1 45.6\n..."的格式),再用re.sub去掉非数字字符,最后得到的是一个单一的长字符串。当你试图把这个结果赋值回9列的DataFrame时,形状自然不匹配——右边是长度为30的Series(如果按行axis=1处理的话),左边是(30,9)的DataFrame,系统无法完成广播。

正确的两种修复方式:

方式1:使用applymap处理每个单元格

applymap是专门用来对DataFrame的每个单元格(标量)执行操作的方法,完美匹配你的需求:

import re
import pandas as pd

numeric_cols = ['temp', 'windchill', 'dewpoint', 'humidity', 'pressure', 'visibility', 'wind_speed', 'gust_speed', 'precip']
# 用applymap逐个处理单元格
weather_list[numeric_cols] = weather_list[numeric_cols].applymap(lambda x: re.sub('[^0-9]', '', str(x)))
weather_list[numeric_cols] = pd.to_numeric(weather_list[numeric_cols], errors='coerce')
weather_list[numeric_cols] = weather_list[numeric_cols] / 10

方式2:使用replace矢量化操作(更高效)

如果这些列原本就是字符串类型,用replace配合regex=True会比applymap更高效,因为它是矢量化的批量操作:

import pandas as pd

numeric_cols = ['temp', 'windchill', 'dewpoint', 'humidity', 'pressure', 'visibility', 'wind_speed', 'gust_speed', 'precip']
# 批量替换所有非数字字符
weather_list[numeric_cols] = weather_list[numeric_cols].replace('[^0-9]', '', regex=True)
weather_list[numeric_cols] = pd.to_numeric(weather_list[numeric_cols], errors='coerce')
weather_list[numeric_cols] = weather_list[numeric_cols] / 10

额外提示:

  • 用errors='coerce'会把无法转成数字的内容变成NaN,之后可以考虑用fillna处理这些缺失值,比如weather_list[numeric_cols] = weather_list[numeric_cols].fillna(0)或者用列均值填充。
  • 如果你不确定列的类型,可以先打印weather_list[numeric_cols].dtypes确认,确保后续操作的正确性。

内容的提问来源于stack exchange,提问作者David Black

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:34:19