我有下面的字典列表,我想使用python将其展平。数据最初来自xero,如下所示:
以下是我使用API提取的示例数据:
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'}]}]}]
所需的输出如下:
Name Amount Hierarchy_level_3 Hierarchy_level_1 Hierarchy_level_2
0 Contract Rent 721093.92 Rent Received Income Income from Rents
1 Rent - Carparks 3523.33 Rent Receive Income Income from Rents
2 Vacant Tenancies -22226.50 Rent Received Income Income from Rents
3 Total Rent Received 702390.75
4 COVID-19 Rent reduction -132478.03 Rent Reduction Income Income from Rents
. . . . . .
. . . . . .
有谁能帮我实现这个目标吗?这里的示例数据是我从api获得的格式。不确定如何展平此文件。我对Python相对较新
假设示例中第
4
行的Hierarchy_level_3
是Rent Received
而不是Rent Reduction
,并且示例中有一个级别4的层次结构,下面是一个解决方案。我添加了级别编号和级别名称,因为我认为它们可能比“层次级别”更有用,但可以随意删除输出:
-编辑 由于只需要3级层次结构:
输出:
相关问题 更多 >
编程相关推荐