如何解决KeyError: '[True] not in index'错误并写入统计结果
问题解决指南
一、筛选price_oh非零值的错误修正
你之前的代码报错是因为错误地把条件判断写在了列名列表里:"price_oh" != 0.00会直接返回布尔值True,pandas会尝试查找名为True的列,而你的数据里没有这一列,所以触发KeyError。
正确的做法是先选择需要的列,再过滤符合条件的行,或者用.loc同时完成列选择和行过滤,两种写法如下:
写法1:分步操作
# 先选择目标列 df2 = df[["match","hteam_name", "ateam_name", "price_oh", "price_oa", "bookmaker_name"]] # 过滤price_oh非零的行 df2 = df2[df2["price_oh"] != 0.00].reset_index(drop=True)
写法2:用.loc一次性完成
df2 = df.loc[df["price_oh"] != 0.00, ["match","hteam_name", "ateam_name", "price_oh", "price_oa", "bookmaker_name"]].reset_index(drop=True)
二、将分组均值结果合并到原数据中
要把df2.groupby(["match"]).mean()的结果作为列加入原数据,有两种常用方法:
方法1:用merge合并(适合先查看单独的均值表再合并)
import pandas as pd # 计算每个赛事的均值,并给新列重命名 match_mean = df2.groupby(["match"])[["price_oh", "price_oa"]].mean() match_mean = match_mean.rename(columns={ "price_oh": "mean_price_oh", "price_oa": "mean_price_oa" }).reset_index() # 将均值表与原数据按match列合并 df2_with_mean = pd.merge(df2, match_mean, on="match", how="left")
方法2:用transform直接生成新列(更简洁)
transform会自动将分组计算的均值映射到每一行,直接在原DataFrame中添加新列:
df2["mean_price_oh"] = df2.groupby(["match"])["price_oh"].transform("mean") df2["mean_price_oa"] = df2.groupby(["match"])["price_oa"].transform("mean")
内容的提问来源于stack exchange,提问作者Borja Alamo
相关产品推荐
相关产品推荐

