【问题标题】:Reading several nested .json files from a specific folder, into excel using python/pandas使用 python/pandas 从特定文件夹中读取几个嵌套的 .json 文件到 excel 中
【发布时间】:2021-02-27 11:03:36
【问题描述】:

我想将文件夹中的几个嵌套 json 文件读入一个 excel 文件。 由于大多数.json文件彼此不同(每个文件中有不同的嵌套级别),这也意味着excel文件中的某些列(值)显然需要为NaN。我用这段代码读取特定文件没有问题,但是要一个一个读取10 000个需要一段时间。

import json 
import pandas as pd 
from pandas.io.json import json_normalize 

with open('file1.json','r') as f: #Here I want help, since i need to read 10 000 json files.
    data = json.loads(f.read())
multiple_level_data = pd.json_normalize(data, record_path =['data'], errors='ignore', meta =['total-count'], meta_prefix='config_params_', record_prefix='dbscan_')
multiple_level_data.to_excel('file1converted.xlsx', index=False)

但是,如何修改我的 python 代码以读取文件夹中的所有 json 文件,而不仅仅是 file1.json?

【问题讨论】:

    标签: python json excel pandas


    【解决方案1】:

    以上来自 Wasif 的解决方案效果很好, 但是我添加了这个以将其放入一个 excel 文件中。

    df = pd.DataFrame()
    for file in files:
         if file.endswith('.xlsx'):
             df = df.append(pd.read_excel(file, engine='openpyxl'), ignore_index=True) 
    df.to_excel("AllJsonFilesInOneExcel.xlsx")
    

    谢谢。

    【讨论】:

      【解决方案2】:

      你可以试试os.listdir():

      import os
      import json 
      import pandas as pd 
      from pandas.io.json import json_normalize 
      
      for js in [x for x in os.listdir() if x.endswith('.json')]:
        with open(js,'r') as f: 
          data = json.loads(f.read())
          multiple_level_data = pd.json_normalize(data, record_path =['data'], errors='ignore', meta =['total-count'], meta_prefix='config_params_', record_prefix='dbscan_')
          multiple_level_data.to_excel(js+'converted.xlsx', index=False)
      

      【讨论】:

      • 谢谢 Wasif,这似乎工作得很好,但是,它为每个 json 文件创建了一个 excel 文件。是否可以代替为每个 .json 创建 10 000 个 excel 文件,而是将此 for 循环合并到一个具有 10 000 行的 excel 文件中?
      猜你喜欢
      • 2015-08-12
      • 2021-06-17
      • 1970-01-01
      • 2019-10-01
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      • 2021-02-02
      • 2013-06-08
      相关资源
      最近更新 更多