【问题标题】:Converting Json to Excel or CSV in Python在 Python 中将 Json 转换为 Excel 或 CSV
【发布时间】:2018-07-17 04:47:48
【问题描述】:

我有一个 JSON 文档,我想将其转换为 Excel 或 CSV。我的 JSON 文件如下所示:

df = pd.DataFrame(columns=[Store,Address,User,Rating], dtype='unicode')

有以下数据:

 Store  |   Address  |  User   | Rating  
|:----------------------------------------:|
 Store X| Adresse X  | User 1  | 3
        |            | User 2  | 5
        |            | User 3  | 2
 Store Y| Adresse Y  | User 1  | 2
        |            | User 2  | 1
        |            | User 3  | 4
        |            | User 4  | 5

我尝试使用以下代码将 Json Doc 转换为 Excel:

jsonDoc = pd.read_json(df.to_json())
ExcelDoc = jsonDoc.to_excel("C:\Users\output.xlsx")

但我得到以下输出:

 Store  |   Address  |  User                    | Rating  
|:-------------------------------------------------------:|
 Store X| Adresse X  | User 1,User2,User3       | 3,5,2
 Store Y| Adresse Y  | User 1,User2,User3,User4 | 2,1,4,5

但我希望我的 excel 文件是这样的:

 Store  |   Address  |  User   | Rating  
|:----------------------------------------:|
 Store X| Adresse X  | User 1  | 3
 Store X| Adresse X  | User 2  | 5
 Store X| Adresse X  | User 3  | 2
 Store Y| Adresse Y  | User 1  | 2
 Store Y| Adresse Y  | User 2  | 1
 Store Y| Adresse Y  | User 3  | 4
 Store Y| Adresse Y  | User 4  | 5

有人可以帮助我吗?我该如何实现呢?有没有可以处理的库?

【问题讨论】:

    标签: python json excel csv


    【解决方案1】:

    我只做了一个月,但我主要是使用和学习 .json 和 .xlsx,因为这主要是我需要 python 的。

    我使用和喜欢的主要是 Tablib。当我需要更多的 excel 功能时,我会使用 Openpyxl。

    http://docs.python-tablib.org/en/master/api/

    data = tablib.Dataset(headers=('Store', 'Address', 'User', 'Rating'))
    

    有几种方法可以将数据导入 tablib,我更喜欢下面的方法,因为它也适用于 Databooks(多个数据集)。

    import tablib
    
    import_filename = 'jsondatafile.json'
    data.json = open(import_filename, 'r').read()
    

    要将其转换为 xlsx 或 csv:

    print(data.xlsx)
    print(data.csv)
    

    将其写入文件:

    data_export = data.export('xlsx')
    with open('C:/file.xlsx', 'wb') as f:  # open the xlsx file
        f.write(data_export)  # write the dataset to the xlsx file
    f.close()
    

    Tablib 的功能令人惊叹,请查看他们的 API 或获取快速入门指南。

    【讨论】:

      猜你喜欢
      • 2021-02-11
      • 1970-01-01
      • 2014-11-19
      • 2016-11-30
      • 1970-01-01
      • 1970-01-01
      • 2023-01-24
      • 2015-08-07
      • 1970-01-01
      相关资源
      最近更新 更多