【问题标题】:Translating column-wise JSON data from Excel into a hierarchical structure with python使用 python 将 Excel 中的按列 JSON 数据转换为层次结构
【发布时间】: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)"]}}'

【问题讨论】:

    标签: python json excel pandas


    【解决方案1】:

    你可以这样做:

    import pandas as pd
    import json
    from collections import defaultdict
    
    path = "Some Path/test.xlsx"
    df = pd.read_excel(path,
                       engine='openpyxl',
                       # header=None, names=['Block', 'Task', 'Code']  # only if your file has no headers
                       )
    
    df.dropna(inplace=True, axis=0, how='all')
    df.fillna(method='ffill', inplace=True, axis=0)
    df = df.set_index(['Block', 'Task'])
    
    nested_dict = defaultdict(lambda : defaultdict(list))
    
    for keys, value in df.Code.iteritems():
        nested_dict[keys[0]][keys[1]].append(value)
    
    json_str = json.dumps(nested_dict, indent=4, sort_keys=True)
    print(json_str)
    

    输出:

    {
        "* 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)"
            ]
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-05
      • 1970-01-01
      • 2016-06-04
      • 2023-03-31
      相关资源
      最近更新 更多