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

如何使用sklearn.mean_absolute_error为数据集每行生成MAE列?

计算每行商品的平均绝对误差(MAE)

现有数据集如下:

NameJan QtyFeb QtyMar QtyJan FcstFeb FcstMar Fcst
Banana105237424
Apple53328717

要为每个商品(每行)计算实际值与预测值的平均绝对误差,可通过以下代码实现:

import pandas as pd
from sklearn.metrics import mean_absolute_error

# 构造数据集
data = {
    'Name': ['Banana', 'Apple'],
    'Jan Qty': [10, 5],
    'Feb Qty': [5, 3],
    'Mar Qty': [23, 32],
    'Jan Fcst': [7, 8],
    'Feb Fcst': [4, 7],
    'Mar Fcst': [24, 17]
}
df = pd.DataFrame(data)

# 定义逐行计算MAE的函数
def calculate_mae(row):
    y_true = [row['Jan Qty'], row['Feb Qty'], row['Mar Qty']]
    y_pred = [row['Jan Fcst'], row['Feb Fcst'], row['Mar Fcst']]
    return mean_absolute_error(y_true, y_pred)

# 添加MAE列
df['MAE'] = df.apply(calculate_mae, axis=1)

print(df)

运行结果

执行上述代码后,得到带MAE列的数据集:

NameJan QtyFeb QtyMar QtyJan FcstFeb FcstMar FcstMAE
Banana1052374242.0
Apple533287179.0

计算说明

  • Banana的MAE:(|10-7| + |5-4| + |23-24|)/3 = (3+1+1)/3 ≈ 2.0
  • Apple的MAE:(|5-8| + |3-7| + |32-17|)/3 = (3+4+15)/3 ≈ 9.0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 10:05:29