【发布时间】:2021-04-04 03:53:08
【问题描述】:
总体目标
我的总体目标是将 Excel 文件中的输入转换为文本文件(Stata .do 文件),以执行一组数据协调任务,这些任务具有大致相同的结构,但由于数据的特殊性而需要单独处理数据(国家调查)。协调将由不同的人执行,Excel 确保人们使用相同的结构。我的策略是读取 JSON 结构的 Excel 文件,使用这个结构写入 do 文件。
我请求帮助的任务
我现在要解决的问题是如何将 JSON 从 Excel 中读取时的列结构转变为层次结构。我希望用户拥有的 Excel 文件具有块内的块和任务结构,以及执行任务所需的特定命令(一行或多行)。下图是 Excel 文档的示例:
最终目标是生成这样的文本文件:
* A
* A1
Command for A1
* A2
Command for A2 (1)
Command for A2 (2)
* B
* B1
Command for B1 (1)
Command for B1 (2)
Command for B1 (3)
*B2
Command for B2 (1)
Command for B2 (2)
我使用 Python 使用以下代码读取此内容:
path = "Some Path/test.xlsx"
import pandas
import json
x = pandas.read_excel(path, sheet_name='Sheet')
json_str = x.to_json()
如前所述,这会产生 JSON 的列结构,如下所示:
我正在努力将其转换为代码自然具有的层次结构。我想要的输出是这种形式的 JSON 对象:
如果有更聪明的方法来实现总体目标,我很高兴知道它,但我认为这种翻译是构建信息的必要步骤。
这里是生成 JSON 对象以便重现的代码
# Column-wise object
'{"Block":{"0":"* A","1":null,"2":null,"3":null,"4":null,"5":null,"6":"* B","7":null,"8":null,"9":null,"10":null,"11":null},"Task":{"0":"* A1","1":null,"2":null,"3":"* A2","4":null,"5":null,"6":"* B1","7":null,"8":null,"9":null,"10":"*B2","11":null},"Code":{"0":"Command for A1","1":null,"2":null,"3":"Command for A2 (1)","4":"Command for A2 (2)","5":null,"6":"Command for B1 (1)","7":"Command for B1 (2)","8":"Command for B1 (3)","9":null,"10":"Command for B2 (1)","11":"Command for B2 (2)"}}'
# Hierarchical object
'{"* A": {"* A1": ["Command for A1"], "* A2": ["Command for A2 (1)", "Command for A2 (2)"] }, "* B" : {"* B1" : ["Command for B1 (1)", "Command for B1 (2)", "Command for B1 (3)"], "* B2" : ["Command for B2 (1)", "Command for B2 (2)"]}}'
【问题讨论】: