将嵌套的JSON结构转换为Pandas DataFrames
在这篇文章中,我们将看到如何将嵌套的JSON结构转换为Pandas DataFrames。
JSON有多个层次
在这种情况下,嵌套的JSON数据包含另一个JSON对象作为其某些属性的值。这使得数据成为多层次的,我们需要根据项目要求将其扁平化,以获得更好的可读性,如下所述。
# importing the libraries used
import pandas as pd
# initializing the data
data = {
'company': 'XYZ pvt ltd',
'location': 'London',
'info': {
'president': 'Rakesh Kapoor',
'contacts': {
'email': 'contact@xyz.com',
'tel': '9876543210'
}
}
}
这里,数据包含多个层次。为了将其转换为数据框架,我们将使用pandas库的json_normalize()函数。
pd.json_normalize(data)
输出:
json数据转换为pandas数据框架
在这里,我们看到数据被压平并转换为列。如果我们不希望完全扁平化数据,我们可以使用max_level属性,如下所示。
pd.json_normalize(data,max_level=0)
输出:
json数据转换为pandas数据框架
在这里,我们看到信息栏没有被进一步扁平化。
pd.json_normalize(data,max_level=1)
输出:
json数据转换为pandas数据框架
在这里,我们看到联系栏没有被进一步拉平。
嵌套的JSON列表
现在,如果数据是一个嵌套的JSON列表,我们将在我们的数据框架中得到多条记录。
data = [
{
'id': '001',
'company': 'XYZ pvt ltd',
'location': 'London',
'info': {
'president': 'Rakesh Kapoor',
'contacts': {
'email': 'contact@xyz.com',
'tel': '9876543210'
}
}
},
{
'id': '002',
'company': 'PQR Associates',
'location': 'Abu Dhabi',
'info': {
'president': 'Neelam Subramaniyam',
'contacts': {
'email': 'contact@pqr.com',
'tel': '8876443210'
}
}
}
]
pd.json_normalize(data)
输出:
json数据转换为pandas数据框架
因此,在JSON的多个层次的情况下,我们可以尝试不同的max_level属性的值。
JSON与嵌套列表
在这种情况下,嵌套的JSON有一个JSON对象的列表作为其某些属性的值。在这种情况下,我们可以使用record_path属性选择内部列表项作为我们数据框架的记录/行。
# initialising the data
data = {
'company': 'XYZ pvt ltd',
'location': 'London',
'info': {
'president': 'Rakesh Kapoor',
'contacts': {
'email': 'contact@xyz.com',
'tel': '9876543210'
}
},
'employees': [
{'name': 'A'},
{'name': 'B'},
{'name': 'C'}
]
}
# converting the data to dataframe
df = pd.json_normalize(data)
输出:
json数据转换为pandas数据帧
在这里,嵌套的列表没有被平整化。我们需要使用record_path属性来平整嵌套的列表。
pd.json_normalize(data,record_path=['employees'])
输出:
嵌套列表没有被平整化
现在,我们观察到它不包括 “信息 “和其他特征。为了包括它们,我们使用另一个属性,meta. 注意,在下面的代码中,为了包括内部JSON的一个属性,我们指定路径为”[‘info’, ‘peace’]”。
pd.json_normalize(data, record_path=['employees'], meta=[
'company', 'location', ['info', 'president']])
输出:
json数据转换为pandas数据框架
现在在多个嵌套的JSON对象的情况下,我们将得到一个有多条记录的数据框架,如下图所示。
data = [
{
'id': '001',
'company': 'XYZ pvt ltd',
'location': 'London',
'info': {
'president': 'Rakesh Kapoor',
'contacts': {
'email': 'contact@xyz.com',
'tel': '9876543210'
}
},
'employees': [
{'name': 'A'},
{'name': 'B'},
{'name': 'C'}
]
},
{
'id': '002',
'company': 'PQR Associates',
'location': 'Abu Dhabi',
'info': {
'president': 'Neelam Subramaniyam',
'contacts': {
'email': 'contact@pqr.com',
'tel': '8876443210'
}
},
'employees': [
{'name': 'L'},
{'name': 'M'},
{'name': 'N'}
]
}
]
df = pd.json_normalize(data, record_path=['employees'], meta=[
'company', 'location', ['info', 'president']])
print(df)
输出 :
json数据转换为pandas数据框架