【发布时间】:2016-10-26 10:33:09
【问题描述】:
我现在已将当前问题添加到 GitHib。请找到 repo 的 URL。我已经包含了一个 Jupyter 笔记本,它也解释了这个问题。谢谢大家。
https://github.com/simongraham/dataExplore.git
我目前正在为一个项目处理营养数据,其中数据是原始 JSON 格式,我想使用 python 和 pandas 来获得一个可以理解的数据框。我知道当 JSON 没有嵌套时,这是一项简单的任务。在这里我会使用:
nutrition = pd.read_json('data')
但是我有嵌套的信息,我发现很难将它放入一个合理的数据框中。 JSON 格式如下,其中 NutritionNutrients 元素本身是一个嵌套元素。此元素的巢将描述各种不同物质的营养成分,例如酒精和 bcfa,包括在内。我只包含了一个示例,因为这是一个大型数据文件。
[
{
"vcNutritionPortionId": "478d1905-f264-4d9b-ab76-0ed4252193fd",
"vcNutritionId": "2476378b-79ee-4857-a81d-489661a039a1",
"vcUserId": "cc51145b-5a70-4344-9b55-1a4455f0a9d2",
"vcPortionId": "1",
"vcPortionName": "1 average pepper",
"vcPortionSize": "20",
"ftEnergyKcal": 5.2,
"vcPortionUnit": "g",
"dtConsumedDate": "2016-05-04T00:00:00",
"nutritionNutrients": [
{
"vcNutritionPortionId": "478d1905-f264-4d9b-ab76-0ed4252193fd",
"vcNutrient": "alcohol",
"ftValue": 0,
"vcUnit": "g",
"nPercentRI": 0,
"vcTrafficLight": ""
},
{
"vcNutritionPortionId": "478d1905-f264-4d9b-ab76-0ed4252193fd",
"vcNutrient": "bcfa",
"ftValue": 0,
"vcUnit": "g",
"nPercentRI": 0,
"vcTrafficLight": ""
},
{
"vcNutritionPortionId": "478d1905-f264-4d9b-ab76-0ed4252193fd",
"vcNutrient": "biotin",
"ftValue": 0,
"vcUnit": "µg",
"nPercentRI": 0,
"vcTrafficLight": ""
},
...
]
}
]
任何帮助将不胜感激。
谢谢。
.... ....
现在我已经找到了如何使用 json_normalize 解决这个问题,我返回了同样的问题,但是这次我的代码嵌套了两次。即:
[
{
...
}
[,
"nutritionPortions": [
{
"vcNutritionPortionId": "478d1905-f264-4d9b-ab76-0ed4252193fd",
"vcNutritionId": "2476378b-79ee-4857-a81d-489661a039a1",
"vcUserId": "cc51145b-5a70-4344-9b55-1a4455f0a9d2",
"vcPortionId": "1",
"vcPortionName": "1 average pepper",
"vcPortionSize": "20",
"ftEnergyKcal": 5.2,
"vcPortionUnit": "g",
"dtConsumedDate": "2016-05-04T00:00:00",
"nutritionNutrients": [
{
"vcNutritionPortionId": "478d1905-f264-4d9b-ab76-0ed4252193fd",
"vcNutrient": "alcohol",
"ftValue": 0,
"vcUnit": "g",
"nPercentRI": 0,
"vcTrafficLight": ""
},
{
"vcNutritionPortionId": "478d1905-f264-4d9b-ab76-0ed4252193fd",
"vcNutrient": "bcfa",
"ftValue": 0,
"vcUnit": "g",
"nPercentRI": 0,
"vcTrafficLight": ""
},
{
"vcNutritionPortionId": "478d1905-f264-4d9b-ab76-0ed4252193fd",
"vcNutrient": "biotin",
"ftValue": 0,
"vcUnit": "µg",
"nPercentRI": 0,
"vcTrafficLight": ""
},
...
}
]
}
]
如果我的 JSON 仅包含我可以使用的营养数据:
nutrition = (pd.io
.json
.json_normalize((data, ['nutritionPortions']), 'nutritionNutrients',
['vcNutritionId','vcUserId','vcPortionId','vcPortionName','vcPortionSize',
'ftEnergyKcal','vcPortionUnit','dtConsumedDate'])
)
但是,我的数据不仅包含营养信息。例如,它将包含活动信息,因此营养信息在开头嵌套了“nutrtitionPortions”。假设所有其他列都没有嵌套,它们由“Activity”和“Wellbeing”表示。
如果我使用代码:
nutrition = (pd.io
.json
.json_normalize(data, ['nutritionPortions'])
)
我会回到原来嵌套“nutritionNutrients”的问题,但是我没有成功然后获得相应的数据框。
谢谢
【问题讨论】:
标签: python json pandas dataframe