python - 如何将 json 文件中的特定键插入到 Python 中的数据框中

标签 python json pandas dataframe

如果这很简单或者已经被问过,我很抱歉,我是 Python 新手并且使用 json 文件,所以我很困惑。

我有一个从网站上抓取的 9 GB json 文件。该数据包含约 300 万人的信息。每个人都有属性,但并不是所有的人都具有相同的属性。一个属性对应于 json 文件中的一个键,如下所示:

{
  "_id": "in-00000001",
  "name": {
    "family_name": "Trump",
    "given_name": "Donald"
  },
  "locality": "United States",
  "skills": [
    "Twitter",
    "Real Estate",
    "Golf"
     ],
  "industry": "Government",
  "experience": [
  {
    "org": "Republican",
    "end": "Present",
    "start": "January 2017",
    "title": "President of the United States"
  },
  {
    "org": "The Apprentice",
    "end": "2015",
    "start": "2003",
    "title": "The guy that fires people"
  }]
}

所以在这里,_id名称地点技能行业经验是属性(键)。另一个个人资料可能具有其他属性,例如教育奖项兴趣,或者缺少其他个人资料中的某些属性,例如技能 属性,等等。

我想要做的是扫描 json 文件中的每个个人资料,并且个人资料是否包含属性 skillsindustryexperience,我想提取该信息并将其插入到数据框中(我想我需要 Pandas 吗?)。根据经验,我想专门提取他们当前雇主的名称,即org下的最新列表。数据框如下所示:

    Industry   | Current employer | Skills
    ___________________________________________________________________
    Government | Republican       | Twitter, Real Estate, Golf
    Marketing  | Marketers R Us   | Branding, Social Media, Advertising

...对于具有这三个属性的所有配置文件,依此类推。

我正在努力寻找一个好的资源来解释如何做这种事情,因此我提出了这个问题。

我想粗略的伪代码是:

for each profile in open(path to .json file):
    if profile has keys "experience", "industry" AND "skills":
        on the same row of the data frame:
            insert current employer into "current employer" column of 
            data frame
            insert industry into "industry" column of data frame
            insert list of skills into "skills" column of data frame

我只需要知道如何用 Python 编写它。

最佳答案

我假设该文件包含所有配置文件,例如

{
    "profile 1" : {
        # Full object as in the example above
    },
    "profile 2" : {
        #Full object as in the example above
    }
}

在继续之前,让我展示一下使用 Pandas DataFrames 的正确方法。

更好地使用 Pandas DataFrames 的示例:

Pandas DataFrame 中的值不能是列表。因此,我们必须复制行,如下例所示。查看此问题和 JD Long 的回答以获取更多详细信息:how to use lists as values in pandas dataframe?

ID      |    Industry   | Current employer | Skill
___________________________________________________________________
in-01   |    Government | Republican       | Twitter
in-01   |    Government | Republican       | Real Estate
in-01   |    Government | Republican       | Golf
in-02   |    Marketing  | Marketers R Us   | Branding
in-02   |    Marketing  | Marketers R Us   | Social Media
in-02   |    Marketing  | Marketers R Us   | Advertising

在以下代码的注释中查找解释:

import json
import pandas as pd

# Create a DataFrame df with the columns as in the example
df = pd.DataFrame(data, columns = ['ID', 'Industry','Employer','Skill']) 

#Load the file as json. 
with open(path to .json file) as file:
    #readlines() reads the file as string and loads() loads it into a dict
    obj = json.loads(''.join(file.readlines()))
    #Then iterate its items() as key value pairs
    #But the line of code below depends on my first assumption.
    #Depending on the file format, the line below might have to differ.
    for prof_key, profile in obj.items():
        # Verify if a profile contains all the required keys
        if all(key in profile.keys() for key in ("_id","experience", "industry","skills")):
            for skill in profile["skills"]:
                df.loc[-1] = [profile["_id"],
                              profile["industry"],
                              [x for x in profile["experience"] if x["end"] == "Present"][0]["org"],
                              skill]

上面的行 df.loc[-1] = ... 在数据帧中插入一行作为最后一行(索引 -1)。

当您稍后想要使用此信息时,您必须使用df.groupby('ID')

请告诉我您的文件中是否有不同的格式,以及此说明是否足以帮助您入门或您需要更多信息。

关于python - 如何将 json 文件中的特定键插入到 Python 中的数据框中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58358444/

相关文章:

python - 如何在每个记录器的基础上更改 Python 日志消息的格式?

python - 在 Python 中将十六进制字符串转换为整数

asp.net - 返回 JSON 列表并在 MVC 4 View 页面上使用

javascript - JSON 未被 jQuery 解析(给出错误)

python - 从分组数据框中获取百分位数

python - 对列表内的值进行分组

java - 使用 Hibernate 将 json 值插入到 postgresql 表中

python - 从数据框列列表创建术语频率字典

python - 属性错误 : 'Series' object has no attribute 'rolling'

virtualenv 中的 Python ctypes 导入错误