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

Pandas分组聚合时访问'Total Revenue'触发KeyError问题求助

问题分析与解决方案

错误原因

你代码里的KeyError: 'Total Revenue'是因为在'Guest Type'列的聚合逻辑中,lambda函数的参数x仅代表分组后的Guest Type列本身——它是一个只包含Guest Type取值的Series,根本没有Total Revenue这个字段,所以你尝试从里面提取'Total Revenue'时必然报错。

你的需求是按Country分组后,计算组内Guest Type为'New Guest'的Total Revenue总和,这个逻辑不能绑定在'Guest Type'的聚合参数里,因为lambda的作用域只限于当前列。

修复方案

下面提供两种简洁易读的实现方式:

方式一:使用groupby.apply()直接处理分组

这种方式可以直接访问整个分组的DataFrame,逻辑更直观:

import pandas as pd

def agg_country_group(group):
    return pd.Series({
        'Country': group['Country'].iloc[0],
        'Email_nunique': group['Email'].nunique(),
        'Unique_Trip_Count_sum': group['Unique Trip Count'].sum(),
        'Total_Length_of_Stay_sum': group['Total Length of Stay'].sum(),
        'Total_Revenue_sum': group['Total Revenue'].sum(),
        'New_Guest_Count': group[group['Guest Type'] == 'New Guest'].shape[0],
        'Non_New_Guest_Count': group[group['Guest Type'] != 'New Guest'].shape[0],
        'New_Guest_Total_Revenue': group[group['Guest Type'] == 'New Guest']['Total Revenue'].sum()
    })

guest2023_agg = agg_df_2023.groupby('Country').apply(agg_country_group).reset_index(drop=True)

方式二:拆分计算后合并

先计算基础聚合项,再单独计算New Guest的收入,最后合并结果,适合逻辑拆分清晰的场景:

# 1. 计算基础聚合指标
base_agg = agg_df_2023.groupby('Country').agg(
    Email_nunique=('Email', 'nunique'),
    Unique_Trip_Count_sum=('Unique Trip Count', 'sum'),
    Total_Length_of_Stay_sum=('Total Length of Stay', 'sum'),
    Total_Revenue_sum=('Total Revenue', 'sum'),
    New_Guest_Count=('Guest Type', lambda x: (x == 'New Guest').sum()),
    Non_New_Guest_Count=('Guest Type', lambda x: (x != 'New Guest').sum())
).reset_index()

# 2. 单独计算New Guest的总营收
new_guest_revenue = agg_df_2023[agg_df_2023['Guest Type'] == 'New Guest'].groupby('Country').agg(
    New_Guest_Total_Revenue=('Total Revenue', 'sum')
).reset_index()

# 3. 合并结果,空值填0(处理没有New Guest的国家)
guest2023_agg = base_agg.merge(new_guest_revenue, on='Country', how='left').fillna(0)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 20:48:28