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

如何基于另一个DataFrame对目标DataFrame进行分组聚合

解决方案

1. 构建初始DataFrame

首先用pandas创建你提供的两个DataFrame:

import pandas as pd

# 第一个DataFrame(年度数据)
df_yearly = pd.DataFrame({
    'Year': [2019, 2020, 2021, 2022, 2023],
    'F1': [8, 9, 10, 11, 12],
    'F2': [1, 1, 2, 1, 1],
    'F3': [3, 3, 4, 5, 5],
    'F4': [4, 6, 5, 9, 9],
    'F5': [6, 1, 1, 8, 8]
}).set_index('Year')

# 第二个DataFrame(F列与ASSET映射)
df_mapping = pd.DataFrame({
    'ID': ['F1', 'F2', 'F3', 'F4', 'F5'],
    'ASSET': ['carac3', 'carac1', 'carac1', 'carac2', 'carac2']
})

2. 数据处理步骤

通过转置、合并、分组求和并格式化输出:

# 转置年度数据,让F列作为行,便于和映射表匹配
df_transposed = df_yearly.T.reset_index().rename(columns={'index': 'ID'})

# 合并映射表,建立F列与ASSET的关联
merged_df = pd.merge(df_transposed, df_mapping, on='ID')

# 定义格式化函数,生成"=总和 (数值1+数值2+...)"的格式
def format_group_sum(row):
    # 提取年度数值并转为字符串
    value_strs = [str(val) for val in row.drop(['ID', 'ASSET'])]
    # 计算总和
    total = row.drop(['ID', 'ASSET']).sum()
    # 返回格式化后的字符串
    return f'={total} ({"+".join(value_strs)})'

# 按ASSET分组,应用格式化函数后转置结果
final_result = merged_df.groupby('ASSET').apply(format_group_sum).T

3. 最终结果

执行上述代码后,得到的结果如下:

Yearcarac1carac2carac3
2019=4 (1+3)=10 (4+6)=8 (8)
2020=4 (1+3)=7 (6+1)=9 (9)
2021=6 (2+4)=6 (5+1)=10 (10)
2022=6 (1+5)=17 (9+8)=11 (11)
2023=6 (1+5)=17 (9+8)=12 (12)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 15:15:04