从复杂的嵌套字典创建数据帧?

2024-04-20 14:13:15 发布

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

我有一个大的嵌套,然后嵌套的json文件保存为.txt格式。我需要访问一些特定的密钥对,并装箱一个数据帧或另一个转换后的json对象以供进一步使用。这是一个有2对钥匙的小样本。在

[
  {
"ko_id": [819752],
"concepts": [
  {
    "id": ["11A71731B880:http://ontology.intranet.com/Taxonomy/116@en"],
    "uri": ["http://ontology.intranet.com/Taxonomy/116"],
    "language": ["en"],
    "prefLabel": ["Client coverage & relationship management"]
  }
]
  },
  {
"ko_id": [819753],
"concepts": [
  {
    "id": ["11A71731B880:http://ontology.intranet.com/Taxonomy/116@en"],
    "uri": ["http://ontology.intranet.com/Taxonomy/116"],
    "language": ["en"],
    "prefLabel": ["Client coverage & relationship management"]
     }
   ]
 }
]

下面的代码以列表形式加载数据,但我需要访问数据,可能是作为字典访问数据,我需要每个密钥对中的“ko_uid”、“uri”和“prefLabel”,并将其放入pandas数据框或字典中进行进一步分析。在

^{pr2}$

下面的代码给出了第一个元素的确切值。但实际上不知道如何将其组合起来,并构建最终的算法来创建数据帧。在

print(sample_dict["ko_id"][0])
print(sample_dict["concepts"][0]["prefLabel"][0])
print(sample_dict["concepts"][0]["uri"][0])

Tags: 数据samplecomidhttpuridictko
2条回答

可以使用生成器将数据传递给^{}

import pandas as pd
import json as js

with open('sample_data.txt') as data_file:    
   json_sample = js.load(data_file)

df = pd.DataFrame(data = ((key["ko_id"][0],
                           key["concepts"][0]["prefLabel"][0],
                           key["concepts"][0]["uri"][0]) for key in json_sample),  
                  columns = ("ko_id", "prefLabel", "uri"))

输出:

^{pr2}$
for record in sample_dict:
    df = pd.DataFrame(record['concepts']) 
    df['ko_id'] = record['ko_id']
    final_df = final_df.append(df)

相关问题 更多 >