【问题标题】:How can I turn several json files into a dataframe?如何将多个 json 文件转换为数据框?
【发布时间】:2020-09-03 14:02:13
【问题描述】:

我有一些需要转换为数据帧的 json 文件。到目前为止,我使用简单的 for 循环为数据帧、dat 和 .json 文件名创建了名称列表,如下所示:

import json
import matplotlib.pyplot as plt
import numpy as np
from pandas.io.json import json_normalize
import pandas as pd
import os

match_id_required_l = ['7581', '7529', '8652', '7545', '8658', '7561', '8656'] 

file_name_l = [] 
for i in match_id_required_l: 
    j=str(i)+'.json' 
    file_name_l.append(j)

dataframes_l = []
for i in match_id_required_l: 
    j='df'+str(i) 
    dataframes_l.append(j)
    
data_l = []
for i in match_id_required_l: 
    j='data'+str(i) 
    data_l.append(j)

json_file_l = []
for i in match_id_required_l: 
    j='json_file'+str(i) 
    json_file_l.append(j)

我尝试将它们全部打开为 json 文件,并使用另一个 for 循环将它们转换为数据帧,但失败了,因为显然我犯了一个错误,因此它给出了“太多的值无法解包”错误。下面是我尝试过的for循环:

for i, j in file_name_l, json_file_l:
    with open('XXX/data/YYY/'+i, errors='ignore') as j:
        for n, j in data_l, json_file_l:
            n = json.load(j)

我尝试打开的文件名是正确的,我手动检查了它们。对如何修复它感到好奇,因为它不适合一一打开它们。非常感谢您的支持!

【问题讨论】:

  • 可能在 python 中?
  • 是的,很抱歉忘记说清楚。
  • 所以数据框是熊猫?你应该分享一些代码,因为可能有一些方法可以做到这一点。举例将 json 加载为 dicts 数组或使用 pandas 或....
  • 刚刚编辑了我的问题,我认为这更具解释性。

标签: json dataframe for-loop


【解决方案1】:

你可以像这样直接在 Pandas Data Frames 中加载 json

import pandas as pd
df_data_1 = pd.read_json("filepath_data1.json")

你可以像这样在 pandas 中合并数据框

result = pd.merge(df_data_1, df_data_2 , on='COLUMN_NAME', how='outer')

您还想在此处使用您在代码中使用的库名称标记您的问题。请始终发布一个最小的可简化示例

【讨论】:

  • 非常感谢!我尝试这样做的原因实际上是我必须在将它们转换为数据帧时对其进行 json_normalize()。
  • 我不确定现在是什么问题,抱歉
猜你喜欢
  • 2017-05-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-29
  • 2020-10-31
  • 1970-01-01
  • 2019-08-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多