【问题标题】:from df.to_json and want to replace None with NaN (python)来自 df.to_json 并想用 NaN 替换 None (python)
【发布时间】:2021-10-28 22:11:12
【问题描述】:

我将我的数据框转换为 json 类型:

df_json = df.to_json(orient = "records")

但是通过这种方式,我的 NaN 列被转换为 None,而我实际上希望它们是 NaN。因此,当我将我的数据帧继续到 postgres 时,NaN 列将被读取并提取为 NULL。

我转换数据框时的结果:

no   type
1    All
2    None
3    None

同时,想要的结果:

no   type
1    All
2    NaN
3    NaN

到目前为止,我已经尝试过:

df_json = df.to_json(orient = "records").replace("None", np.NaN)

但我收到错误replace() argument 2 must be str, not float

如何将None 转换为 NaN?

提前致谢。

【问题讨论】:

    标签: python json pandas nan


    【解决方案1】:

    如果需要json,没有NaN/Nones,有转换成nulls。

    可能的替代方案是使用 dictionary 并首先将 Nones 替换为 NaNs:

    df_dict = df.mask(df.isna(), np.nan).to_dict(orient = "records")
    print (df_dict)
    [{'no': 1, 'type': 'All'}, {'no': 2, 'type': nan}, {'no': 3, 'type': nan}]
    

    如果None 是字符串:

    df_dict = df.replace("None", np.NaN).to_dict(orient = "records")
    

    【讨论】:

    • 感谢您的回答。我尝试了第一个答案,它给了我错误the JSON object must be str, bytes or bytearray, not list
    • @nomnom3214 - 当然,但如果 NaN 在 json 中,则 json 无效。
    猜你喜欢
    • 2014-07-07
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 2012-12-19
    • 2019-04-22
    • 1970-01-01
    相关资源
    最近更新 更多