【问题标题】:Pandas json_normalize converts ints to floats when there are null values当有空值时,Pandas json_normalize 将整数转换为浮点数
【发布时间】:2020-01-06 18:41:52
【问题描述】:

我正在尝试使用 json_normalize 将一些 json 扁平化为 pandas 数据框。当没有空值时,它按预期工作:

import pandas as pd
from pandas.io.json import json_normalize

json = [{"test": 1}, {"test": 2}, {"test": 3}]

df = json_normalize(json)

print(df)

返回:

   test
0     1
1     2
2     3

但是,如果我将 {"test": 3} 更改为 {"test": None} 则以下 int64 数据对象将转换为 float64 类型:

   test
0   1.0
1   2.0
2   NaN

有人找到解决此问题的方法吗?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    这是因为整数不能是 NaN 类型。

    一种解决方法可能是将所有内容都保留为字符串:

    json = [{"test": "1"}, {"test": "2"}, {"test": "None"}]
    

    你会得到

       test
    0     1
    1     2
    2  None
    

    【讨论】:

    • 同意,如果要保留None,请转换为String。否则,您也可以删除 NaN,然后​​转换回整数
    猜你喜欢
    • 2018-03-13
    • 2014-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多