如何将规范化的json数据从多个文件导入到一个数据帧中?

2024-09-29 02:27:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有几个目录中的json数据文件,我想导入到Pandas中进行一些数据分析。json的格式取决于目录名中定义的类型。例如

dir1_typeA/
  file1
  file2
  ...
dir1_typeB/
  file1
  file2
  ...
dir2_typeB/
  file1
  ...
dir2_typeA/
  file1
  file2

每个file都包含一个复杂的嵌套json字符串,它将是DataFrame的一行。我将为每个TypeA和TypeB有两个数据帧。以后如果需要的话,我会附加它们。你知道吗

到目前为止,我已经有了所有需要的文件os.步行我试着通过

    import os
    from glob import glob

    PATH = 'dir/filepath'
    files = [y for x in os.walk(PATH) for y in glob(os.path.join(x[0], 'file*'))]

    for file in files:
        with open(issuefile, 'r') as f:
            data = f.read()

        data_json = json_normalize(json.loads(data))
        type = ' '.join(issuefile.split('/')[3]
        data_json['type'] = type
        # append to data frame for typeA and typeB
        if 'typeA' in type:
            # append to typeA dataframe
        else:
            # append to typeB dataframe

另外还有一个问题,即目录中的文件可能有稍微不同的字段。例如,file1可能还有几个字段file2dir1_typeA中。所以,对于每种类型,我也需要在数据帧中适应这种动态特性。你知道吗

如何创建这两个数据帧?你知道吗


Tags: 数据injsonfordataostypefile1
1条回答
网友
1楼 · 发布于 2024-09-29 02:27:05

我认为在将这些文件读入pandas之前,应该首先将它们连接在一起,下面是如何在bash中实现(也可以在Python中实现):

cat `find *typeA` > typeA
cat `find *typeB` > typeB

然后可以使用io.json.json_normalize将其导入熊猫:

import json
with open('typeA') as f:
    data = [json.loads(l) for l in f.readlines()]
    dfA = pd.io.json.json_normalize(data)

dfA

#          that this.first this.second
# 0  otherthing      thing       thing
# 1  otherthing      thing       thing
# 2  otherthing      thing       thing

相关问题 更多 >