简体   繁体   English

如何在文件夹结构中读取多个 json 文件?

[英]How can I read multiple in json files in in folder structure?

I'm trying to read Training data for machine learning in json files, but they are stored in nested folders.我正在尝试读取 json 文件中的机器学习训练数据,但它们存储在嵌套文件夹中。

在此处输入图像描述

I'd like to know how can I read each json file into pandas frame.我想知道如何将每个 json 文件读入 pandas 帧。

Imagine there are three JSON files in a nested folder under data folder.想象一下,数据文件夹下的嵌套文件夹中有三个 JSON 文件。

$ tree data
data
├── date1
│   ├── date2
│   │   └── file1_date2.json
│   └── file1.json
└── file1.json

glob2 module can be used to fetch the JSON files recursively. glob2 模块可用于递归获取 JSON 文件。 glob returns a list of files. glob 返回文件列表

from glob2 import glob
jsonFiles = glob('data/**/*.json') #Can be used absolute or relative paths
print(jsonFiles)
['data/file1.json',  'data/date1/file1.json',  'data/date1/date2/file1_date2.json']

JSON files ban be loaded into dataframe by iterating thru the list jsonFiles . JSON 文件禁止通过遍历列表jsonFiles加载到 dataframe 中。

dfList = []
for jsonFile in jsonFiles:
    df = pd.read_json(jsonFile)
    dfList.append(df)
    
dfTrainingDF = pd.concat(dfList, axis=0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM