将JSON解析为Excel-Pandas + xlwt

时间:2018-08-08 07:47:03

标签: pandas xlwt

我对这个功能还算半途而废。但是,在格式化包含输出的工作表中的数据时,我需要一些帮助。

我当前的代码...

response = {"sic2":[{"confidence":1.0,"label":"73"}],"sic4":[{"confidence":0.5,"label":"7310"}],"sic8":[{"confidence":0.5,"label":"73101000"},{"confidence":0.25,"label":"73102000"},{"confidence":0.25,"label":"73109999"}]}


# Create a Pandas dataframe from the data.
df = pd.DataFrame.from_dict(json.loads(response), orient='index')

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')

# Close the Pandas Excel writer and output the Excel file.
writer.save()

输出如下... enter image description here

我想要的是这样的东西...

enter image description here

我想首先我需要提取和整理标题。 这还包括手动为默认情况下不能包含标题的列分配标题,例如SIC列。

在那之后,我可以将数据及其各自的标题提供给列。

1 个答案:

答案 0 :(得分:3)

您可以遍历json对象的键并从每个键创建一个数据框,然后使用pd.concat将它们组合在一起:

import json

import pandas as pd

response = '{"sic2":[{"confidence":1.0,"label":"73"}],"sic4":[{"confidence":0.5,"label":"7310"}],"sic8":[{"confidence":0.5,"label":"73101000"},{"confidence":0.25,"label":"73102000"},{"confidence":0.25,"label":"73109999"}]}'

json_data = json.loads(response)

all_frames = []
for k, v in json_data.items():
    df = pd.DataFrame(v)
    df['SIC Category'] = k
    all_frames.append(df)

final_data = pd.concat(all_frames).set_index('SIC Category')

print(final_data)

此打印:

              confidence     label
SIC Category                      
sic2                1.00        73
sic4                0.50      7310
sic8                0.50  73101000
sic8                0.25  73102000
sic8                0.25  73109999

您可以像以前一样通过final_data.to_excel(writer, sheet_name='Sheet1')

导出到Excel