pandas json_normalize和JSON中的空值 [英] Pandas json_normalize and null values in JSON

查看:140
本文介绍了 pandas json_normalize和JSON中的空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个样本JSON

I have this sample JSON

{
    "name":"John",
    "age":30,
    "cars": [
        { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
        { "name":"BMW", "models":[ "320", "X3", "X5" ] },
        { "name":"Fiat", "models":[ "500", "Panda" ] }
    ]
 }

当我需要将JSON转换为pandas DataFrame时,我使用以下代码

When I need to convert JSON to pandas DataFrame I use following code

import json
from pandas.io.json import json_normalize
from pprint import pprint

with open('example.json', encoding="utf8") as data_file:
    data = json.load(data_file)
normalized = json_normalize(data['cars'])

此代码效果很好,但是在一些空车(空值)的情况下,我无法进行normalize_json.

This code works well but in the case of some empty cars (null values) I'm not possible to normalize_json.

json的示例

{
    "name":"John",
    "age":30,
    "cars": [
        { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
        null,
        { "name":"Fiat", "models":[ "500", "Panda" ] }
    ]
 }

引发的错误

AttributeError: 'NoneType' object has no attribute 'keys'

我试图忽略json_normalize中的错误,但没有帮助

I tried to ignore errors in json_normalize, but didn't help

normalized = json_normalize(data['cars'], errors='ignore')

我应该如何处理JSON中的空值?

How should I handle null values in JSON?

推荐答案

您可以用空指令填充cars,以防止出现此错误

You can fill cars with empty dicts to prevent this error

data['cars'] = data['cars'].apply(lambda x: {} if pd.isna(x) else x)

这篇关于 pandas json_normalize和JSON中的空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆