簡體   English   中英

從多個 json 文件創建 Pandas dataframe

[英]Creating Pandas dataframe from multiple json files

我有一個充滿 JSON 文件的目錄,我需要從中提取信息並將其轉換為 Pandas dataframe。 我目前的解決方案有效,但我覺得有一種更優雅的方式來做到這一點:

for entry in os.scandir(directory):
    if entry.path.endswith(".json"):
        with open(entry.path) as f:
            data = json.load(f)
            ...
            newline = field1 + ',' + field2 + ',' + ... +  ',' + fieldn
            output.append(newline)
...
df = pd.read_csv(io.StringIO('\n'.join(output)))

是的,這可以做得更好。

import os
import pandas as pd
from glob import glob

all_files = glob(os.path.join(path, "*.json"))
ind_df = (pd.read_json(f) for f in all_files)
df = pd.concat(ind_df, ignore_index=True)

使用生成器將節省大量計算和 memory。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM