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

Python中如何合并求和不同索引的groupby聚合结果?

Hey there! Let's break down how to solve this problem efficiently, with built-in pandas tools that keep things scalable for future changes.

Step 1: Convert GroupBy Objects to DataFrames

First, since GroupBy objects are designed for aggregation rather than merging, we'll convert each one to a DataFrame while preserving the Year and ID index (or reset them to columns if you prefer—either works, but keeping as a multi-index makes merging cleaner).

Assuming your GroupBy objects were created with something like groupby_obj = df.groupby(['Year', 'ID'])['£'].sum(), convert them to named DataFrames to avoid confusion:

# Convert each GroupBy result to a DataFrame with a unique column name
df_set1 = groupby_obj1.to_frame(name='£_set1')
df_set2 = groupby_obj2.to_frame(name='£_set2')

Step 2: Merge with Outer Join to Preserve All Indices

Use an outer join to retain every (Year, ID) pair that exists in either dataset—this handles the "missing index" requirement perfectly:

# Merge the two DataFrames on their multi-index (Year + ID)
merged_df = df_set1.join(df_set2, how='outer')

Alternatively, if you reset the index earlier, use pd.merge with how='outer' and on=['Year', 'ID']—same end result.

Step 3: Sum the £ Columns (Handle Missing Values Automatically)

Pandas' sum() method with skipna=True (default behavior) will treat missing values (from indices that only exist in one dataset) as 0, so you'll get the exact sum you need:

# Calculate total £ across both datasets
merged_df['Total_£'] = merged_df[['£_set1', '£_set2']].sum(axis=1)

Step 4: Make It Scalable for More Datasets

If you ever need to add more GroupBy objects later, just wrap the logic in a loop or use pd.concat to handle any number of datasets:

# Example with 3+ GroupBy objects
groupby_objs = [groupby_obj1, groupby_obj2, groupby_obj3]

# Convert all to DataFrames with unique names
df_list = [obj.to_frame(name=f'£_set{i+1}') for i, obj in enumerate(groupby_objs)]

# Concatenate all DataFrames with outer join
merged_df = pd.concat(df_list, axis=1, join='outer')

# Sum all £ columns (filter by column name pattern to avoid hardcoding)
merged_df['Total_£'] = merged_df.filter(like='£_set').sum(axis=1)

Quick Example of the Output

Suppose your two GroupBy results look like this:

YearID£ (set1)
202210500
202232300
202346700
YearID£ (set2)
202210200
202246400
202332600

Your final merged DataFrame will be:

YearID£_set1£_set2Total_£
202210500200700
202232300NaN300
202246NaN400400
202346700NaN700
202332NaN600600

This keeps all your required indices and sums values where they overlap—exactly what you need!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:20:57