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

Z-Score过滤代码Linux运行正常,Windows环境报ValueError问题求助

错误根因

报错触发自你的第6行代码:

df['Z-Score'] = df[df['Z-Score']==True]

右侧通过布尔条件筛选得到的是行数少于原DataFrame的多列数据集,将其赋值给原DataFrame的单个列时,两者长度完全不匹配。
跨平台运行差异来自两边安装的pandas版本不同:Linux虚拟机上的pandas版本较低,旧版本存在隐式兼容逻辑,会自动给未匹配到的行填充NaN,不会触发报错;Windows上安装的是更高版本的pandas,新版本加入了严格的列长度校验,赋值两侧长度不一致时会直接抛出ValueError: Columns must be same length as key。

修复方案

优化版实现(推荐,逻辑更简洁无冗余)

from scipy import stats

# 直接生成过滤掩码,不需要多余的列赋值操作
z_score = stats.zscore(df['price'])
filter_mask = z_score.between(-3, 3)

# 统计异常值数量
total_outliers = len(filter_mask) - filter_mask.sum()
print(f'Your total outliers were {total_outliers}')

# 过滤异常行并重置索引
df = df[filter_mask].reset_index(drop=True)
print(f'You dropped {total_outliers} rows')
print(df.count())

兼容原有逻辑的最小修改

如果需要保留你原来的代码写法,仅替换错误行即可:

# 把原来的 df['Z-Score'] = df[df['Z-Score']==True] 替换为下行
df.loc[~df['Z-Score'], 'Z-Score'] = pd.NA

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 02:24:03