python - TypeError:NAType 类型的对象不是 JSON 可序列化的
问题描述
预先感谢您的帮助。
我的 python 代码读取 json 输入文件并将数据加载到数据框中,对配置指定的数据框列进行掩码或更改,并在最后阶段创建 json 输出文件。
read json into data frame --> mask/change the df column ---> generate json
输入json:
[
{
"BinLogFilename": "mysql.log",
"Type": "UPDATE",
"Table": "users",
"ServerId": 1,
"BinLogPosition": 2111
}, {
{ "BinLogFilename": "mysql.log",
"Type": "UPDATE",
"Table": "users",
"ServerId": null,
"BinLogPosition": 2111
},
...
]
当我将上述 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
},
....
]
屏蔽逻辑
df['ServerId'] = [fake.pyint() if not(pd.isna(df['ServerId'][index])) else np.nan for index in range(len(df['ServerId']))]
挑战在于,输出“ServerId”应该只包含整数,但不幸的是它包含浮点数。
df['ServerId']
0 9590.0
1 NaN
2 1779.0
3 1303.0
4 NaN
我找到了这个问题的答案,使用“Int64”
df['ServerId'] = df['ServerId'].astype('Int64')
0 8920
1 <NA>
2 9148
3 2434
4 <NA>
然而,使用'Int64',它将 NaN 转换为 NA 并且在写回 json 时,我得到一个错误,
TypeError:NAType 类型的对象不是 JSON 可序列化的
with gzip.open(outputFile, 'w') as outfile:
outfile.write(json.dumps(json_objects_list).encode('utf-8'))
转换为“Int64”数据类型后是否可以保留 NaN?如果这是不可能的,我该如何解决这个错误?
解决方案
推荐阅读
- java - 当设备上还有 WhatsApp Business 时,如何将我的应用程序与 WhatsApp 关联?
- mysql - 如何根据 SQL 中的条件选择多个列?
- python - (Python) 后台键盘输入
- python - 创建后在 FastAPI 中保存图像
- haskell -
:7:36:错误:输入“。”解析错误 当我的源文件中只有“Hello world”时,在命令提示符下使用haskell ghci - syntax-error - APL 中的语法错误(在分配时更改名称类)
- macos - 由于 PyQt dylib 文件未签名或不包含有效时间戳,使用 PyInstaller 构建的应用程序的公证失败
- c - 在 C 中使用 malloc 和 realloc 进行动态内存分配
- vba - MS Word中的VB宏不一致地格式化阿拉伯文本
- keras - 如何从我的测试数据生成器显示错误分类在 keras 中的图像?