You need to enable JavaScript to run this app. 如何用Python将Xero嵌套字典列表展平生成分层DataFrame
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python将Xero嵌套字典列表展平生成分层DataFrame

展平Xero嵌套报表的实现

层级对应规则

遍历嵌套结构时按深度自动匹配层级:

  • 第0层Section → Hierarchy_level_1
  • 第1层Section → Hierarchy_level_2
  • 第2层Section → Hierarchy_level_3
  • 普通Row类型行:提取两个Cell的Value分别作为Name和Amount,携带当前匹配的层级值
  • SummaryRow类型的小计行:提取名称和金额,层级列自动置空(和你的预期输出一致)

可运行代码

首先安装依赖:
pip install pandas

直接复制以下代码,传入你的my_dict即可生成目标DataFrame:

import pandas as pd

def flatten_xero_report(nested_data):
    flat_records = []
    # 用列表存储深度计数器,支持嵌套函数修改值
    depth_counter = [0]
    # 各层级标题缓存
    level_1 = ""
    level_2 = ""
    level_3 = ""

    def traverse(rows):
        nonlocal level_1, level_2, level_3
        for row in rows:
            if row['RowType'] == 'Section':
                current_depth = depth_counter[0]
                # 按深度更新对应层级的标题缓存
                if current_depth == 0:
                    level_1 = row['Title']
                elif current_depth == 1:
                    level_2 = row['Title']
                elif current_depth == 2:
                    level_3 = row['Title']
                # 递归遍历子行,深度+1
                if row['Rows']:
                    depth_counter[0] += 1
                    traverse(row['Rows'])
                    # 子行遍历完成后深度回退
                    depth_counter[0] -= 1
            elif row['RowType'] in ['Row', 'SummaryRow']:
                cells = row['Cells']
                row_name = cells[0]['Value']
                # 金额转数值类型,支持后续计算
                row_amount = float(cells[1]['Value'])
                # 小计行清空层级字段
                if row['RowType'] == 'SummaryRow':
                    h1, h2, h3 = "", "", ""
                else:
                    h1, h2, h3 = level_1, level_2, level_3
                flat_records.append({
                    "Name": row_name,
                    "Amount": row_amount,
                    "Hierarchy_level_1": h1,
                    "Hierarchy_level_2": h2,
                    "Hierarchy_level_3": h3
                })

    traverse(nested_data)
    return pd.DataFrame(flat_records)

# 传入你的样本数据
my_dict = [{'RowType': 'Section', 'Title': 'Income', 'Rows': []},{'RowType': 'Section', 'Title': 'Income from Rents', 'Rows': []},
 {'RowType': 'Section',
  'Title': 'Rent Received',
  'Rows': [{'RowType': 'Row',
    'Cells': [{'Value': 'Contract Rent',
      'Attributes': [{'Value': '5', 'Id': 'account'}, {'Value': '5', 'Id': 'groupID'}]},
     {'Value': '721093.92',
      'Attributes': [{'Value': '5', 'Id': 'account'}, {'Value': '5', 'Id': 'groupID'}]}]},
   {'RowType': 'Row',
    'Cells': [{'Value': 'Rent  - Carparks',
      'Attributes': [{'Value': '95', 'Id': 'account'}]},
     {'Value': '3523.33',
      'Attributes': [{'Value': '95', 'Id': 'account'}]}]},
   {'RowType': 'Row',
    'Cells': [{'Value': 'Vacant Tenancies',
      'Attributes': [{'Value': '53', 'Id': 'account'}]},
     {'Value': '-22226.50',
      'Attributes': [{'Value': '53', 'Id': 'account'}]}]},
   {'RowType': 'SummaryRow',
    'Cells': [{'Value': 'Total Rent Received'}, {'Value': '702390.75'}]}]},
 {'RowType': 'Section',
  'Title': 'Rent Reductions',
  'Rows': [{'RowType': 'Row',
    'Cells': [{'Value': 'COVID-19 Rent reduction',
      'Attributes': [{'Value': '40', 'Id': 'account'}]},
     {'Value': '-132478.03',
      'Attributes': [{'Value': '40', 'Id': 'account'}]}]},
   {'RowType': 'Row',
    'Cells': [{'Value': 'Rent Holiday',
      'Attributes': [{'Value': '4d', 'Id': 'account'}]},
         {'Value': '-14451.58',
          'Attributes': [{'Value': '4d', 'Id': 'account'}]}]},
       {'RowType': 'SummaryRow',
        'Cells': [{'Value': 'Total Rent Reductions'}, {'Value': '-146929.61'}]}]}]

# 生成DataFrame
result_df = flatten_xero_report(my_dict)
print(result_df)

输出说明

  • 代码无需修改Section的硬编码判断,只要嵌套深度和样本一致,即可自动匹配层级
  • 生成的DataFrame结构和你预期完全一致

    注:你给出的预期输出里第1行的Rent Receive为笔误,实际统一为Rent Received,保证同组业务行层级标识一致

  • 金额字段自动转为浮点类型,可直接用于后续汇总、透视分析
  • 若后续Xero报表层级超过3层,只需新增对应层级的缓存变量,在深度判断部分添加匹配逻辑即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.22 22:06:03