TypeError:NAType 类型的对象不可 JSON 序列化

Har*_*ari 5 python numpy dataframe pandas python-3.8

预先感谢您的帮助。

我的 python 代码读取 json 输入文件并将数据加载到数据框中,对配置指定的数据框列进行掩码或更改,并在最后阶段创建 json 输出文件。

read json into data frame --> mask/change the df column ---> generate json
Run Code Online (Sandbox Code Playgroud)

输入json:

[
    {
        "BinLogFilename": "mysql.log",
        "Type": "UPDATE",
        "Table": "users",
        "ServerId": 1,
        "BinLogPosition": 2111
    },        {
    {   "BinLogFilename": "mysql.log",
        "Type": "UPDATE",
        "Table": "users",
        "ServerId": null,
        "BinLogPosition": 2111
    },
  ...
]
Run Code Online (Sandbox Code Playgroud)

当我将上述 json 加载到数据框中时,数据框列“ServerId”具有浮点值,因为它在几个 json 输入块中具有 null 。

主要的中央逻辑将“ServerId”转换/伪造为另一个数字,但输出包含浮点数。

输出json:

[
      {
            "BinLogFilename": "mysql.log",
            "Type": "UPDATE",
            "Table": "users",
            "ServerId": 5627.0,
            "BinLogPosition": 2111
        }, 
        {
            "BinLogFilename": "mysql.log",
            "Type": "UPDATE",
            "Table": "users",
            "ServerId": null,
            "BinLogPosition": 2111
        },
     ....
]
Run Code Online (Sandbox Code Playgroud)

屏蔽逻辑

df['ServerId'] = [fake.pyint() if not(pd.isna(df['ServerId'][index])) else np.nan for index in range(len(df['ServerId']))]
Run Code Online (Sandbox Code Playgroud)

挑战是,输出“ServerId”应该只包含整数,但不幸的是它包含浮点数。

df['ServerId']
0     9590.0
1        NaN
2     1779.0
3     1303.0
4        NaN
Run Code Online (Sandbox Code Playgroud)

我找到了这个问题的答案,使用“Int64”

df['ServerId'] = df['ServerId'].astype('Int64')
0     8920
1     <NA>
2     9148
3     2434
4     <NA>
Run Code Online (Sandbox Code Playgroud)

但是,使用“Int64”,它将 NaN 转换为 NA,并且在写回 json 时,出现错误,

TypeError:NAType 类型的对象不可 JSON 序列化

with gzip.open(outputFile, 'w') as outfile:
    outfile.write(json.dumps(json_objects_list).encode('utf-8'))
Run Code Online (Sandbox Code Playgroud)

转换为“Int64”数据类型后是否可以保留 NaN?如果这是不可能的,我该如何修复该错误?

Edw*_*ere 3

事实上,Pandas NA 和 NaT 不能通过内置 Python json库进行 JSON 序列化。

但是 Pandas DataFrame to_json()方法将为您处理这些值并将它们转换为 JSON null。

from pandas import DataFrame, Series, NA, NaT

df = DataFrame({"ServerId" : Series([8920, NA, 9148, 2434, NA], dtype="Int64") })
s = df.to_json()

# -> {"ServerId":{"0":8920,"1":null,"2":9148,"3":2434,"4":null}}
Run Code Online (Sandbox Code Playgroud)