将多个嵌套的JSON文件读入Pandas DataFrame

时间:2019-11-16 22:48:55

标签: python json pandas dataframe

我在编写从Python文件夹中读取多个json文件的代码时遇到问题。

我的json文件示例(文件名:20191111.json)如下:

[
  {
    "info1": {
      "name": "John",
      "age" : "50"
      "country": "USA",
    },
    "info2": {
      "id1": "129",
      "id2": "151",
      "id3": "196",
    },
    "region": [
      {
        "id": "36",
        "name": "Spook",
        "spot": "2"
      },
      {
        "id": "11",
        "name": "Ghoul",
        "spot": "6"
      },
      {
        "id": "95",
        "lat": "Devil",
        "spot": "4"
      }
    ]
  }
  {
    "info1": {
      "name": "Mark",
      "age" : "33"
      "country": "Brasil",
    },
    "info2": {
      "id1": "612",
      "id2": "221",
      "id3": "850",
    },
    "region": [
      {
        "id": "68",
        "name": "Ghost",
        "spot": "7"
      },
      {
        "id": "75",
        "name": "Spectrum",
        "spot": "2"
      },
      {
        "id": "53",
        "name": "Phantom",
        "spot": "2"
      }
    ]
  }
]

我的代码:

path = 'my_files_directory'
json_files = [pos_json for pos_json in os.listdir(path) if pos_json.endswith('.json')]

df = pd.DataFrame()

for file_ in json_files:
    file_df = pd.read_json(file_ )
    file_df['date'] = file_
    df = df.append(file_df)
    df = df.reset_index(drop=True) 

输出:

             info1                    info2                   region                    date   
0 {'name': 'John', ...}    {'id1': '129', ...}    [{'id':'36','name':'Spook'...     20191111.json
1 {'name': 'Mark', ...}    {'id1': '61', ...}     [{'id':'36','name':'Ghost'...     20191111.json

现在,我删除第一列和第二列,因为这里有不需要的信息。然后我要从“区域”列中提取“名称”信息

我的代码是:

df = df.drop(df.columns[[0,1]], axis=1)
df['name'] = [x[0]['name'] for x in df['region']]

输出:

     name           date   
0    Spook     20191111.json
1    Ghost     20191111.json

但是我希望相应的DataFrame看起来像这样:

      name           date  
0    Spook      20191111.json  
1    Ghoul      20191111.json  
2    Devil      20191111.json  
3    Ghost      20191111.json  
4    Spectrum   20191111.json  
5    Phantom    20191111.json  

要获得它,我必须做什么? 谢谢您的帮助。

1 个答案:

答案 0 :(得分:0)

此代码会影响您的结果,因为您的数据框只有两行:

df['name'] = [x[0]['name'] for x in df['region']]

我将其更改为:

filename = '20191111.json'
df1=pd.read_json(filename)
df1 = df1.drop(columns=['info1', 'info2'])  

df2 = pd.DataFrame(columns=['name', 'date'])
names=[]
dates=[]
for x in df1['region']: 
   for name in x: 
     names.append(name['name']) 
     dates.append(filename)
df2['name']=names
df2['date']=dates 

我得到正确的数据。您列出的理解不能添加比数据框中更多的行,所以我创建了一个新行。