将多个嵌套JSON文件读入DataFram

2024-09-30 08:23:37 发布

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

我在编写从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

现在我删除第一列和第二列,因为有我不需要的信息。然后我想从“region”列中提取“name”信息

我的代码是:

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

但我希望相应的数据帧如下所示:

      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  

我要怎么做才能得到它? 谢谢你的帮助。你知道吗


Tags: 代码nameidjsondfdatefilesregion
1条回答
网友
1楼 · 发布于 2024-09-30 08:23:37

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

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 

我得到了正确的数据。不能添加比数据框中的行更多的行,因此我创建了一个新的行。你知道吗

相关问题 更多 >

    热门问题