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

如何按地点合并多份财务报表至单个DataFrame,保留行项目与年份数据

按地点合并多份财务报表的正确方法

核心思路

要合并多份财务报表且不丢失行项目,同时按地点区分数据,核心步骤是:

  • 为每份报表添加地点标识,确保合并后能溯源数据来源
  • 整合所有报表数据,保留全部行项目、年份及对应数值
  • 清理冗余数据,生成结构化的统一报表

修正后的代码

import pandas as pd
from filing_scraper import scrape_and_process

# 获取报表数据
categories_dict = scrape_and_process()
# 需要处理的报表类型
target_headers = ["Consolidated Balance Sheets", "Consolidated Statements of Operations", "Consolidated Statements of Cash Flows"]

def merge_statements_by_location(df_list, location_names, key_col="Keys"):
    # 为每份报表添加地点列
    labeled_dataframes = []
    for df, loc in zip(df_list, location_names):
        # 确保键列(行项目)在首位
        if key_col in df.columns:
            df = df[[key_col] + [col for col in df.columns if col != key_col]]
        # 标记数据所属地点
        df["Location"] = loc
        labeled_dataframes.append(df)
    
    # 合并所有报表(保留所有行项目)
    combined_df = pd.concat(labeled_dataframes, ignore_index=True)
    
    # 处理同一地点同一项目的重复数据,保留非空值
    combined_df = combined_df.groupby([key_col, "Location"]).first().reset_index()
    
    # 移除全空的行和列,精简报表
    combined_df = combined_df.dropna(axis=0, how="all").dropna(axis=1, how="all")
    
    # 可选:将数据转为宽格式(年份作为列),取消注释即可启用
    # combined_df = combined_df.melt(id_vars=[key_col, "Location"], var_name="Year", value_name="Amount")
    # combined_df = combined_df.pivot(index=[key_col, "Location"], columns="Year", values="Amount").reset_index()
    
    return combined_df

# 定义各报表对应的地点(替换为你的实际地点名称)
location_map = {
    "Consolidated Balance Sheets": ["纽约分部", "伦敦分部", "东京分部"],
    "Consolidated Statements of Operations": ["纽约分部", "伦敦分部", "东京分部"],
    "Consolidated Statements of Cash Flows": ["纽约分部", "伦敦分部", "东京分部"]
}

merged_results = {}

# 批量处理每种类型的报表
for header in target_headers:
    if header in categories_dict:
        df_collection = categories_dict[header]
        # 确保地点数量与报表数量匹配
        if df_collection and len(df_collection) == len(location_map.get(header, [])):
            merged_df = merge_statements_by_location(df_collection, location_map[header])
            merged_results[header] = merged_df

# 输出合并结果
for report_type, df in merged_results.items():
    print(f"=== {report_type} 合并结果 ===\n", df)

关键改进说明

  1. 地点标记:新增Location列,解决了合并后无法区分不同地点数据的问题。
  2. 高效合并:用pd.concat替代多次merge,更适合同结构报表的批量整合,避免列名混乱。
  3. 数据清理:通过groupby去重,确保同一地点同一行项目只保留有效数据;移除全空行/列减少冗余。
  4. 格式灵活:可选的宽格式转换(注释部分)可以将数据转为传统财务报表的列布局,方便后续分析。

注意:location_map中的地点名称必须替换为你的实际分部/地区名称,且数量要和对应类型下的报表数量一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 06:37:04