【发布时间】:2021-01-26 10:24:39
【问题描述】:
我有以下要使用 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 比较陌生。
【问题讨论】:
-
离题: 谨防在 SO(即互联网)上发布公司受限/机密数据。它可能(或可能不会)导致您与雇主之间的问题。当然,您发布的数据可能完全是您自己的财产,我不知道(?)。您可以用虚构的数据替换数字,用一些任意但仍然相关的名称替换键(单元格名称)。
-
ID 已加密,我的个人数据也已加密。这应该不是问题。
标签: python json pandas dictionary for-loop