(存入json文件出错)TypeError: Object of type int64 is not JSON serializable

  • 问题描述

    因为numpyint类型无法被json化,所以需要将numpyint转为原生类型。

  • 解决方案

    # pandas返回的
    sex_cnt = marks['sex'].value_counts()
    type(sex_cnt['男']) # numpy.int64
    
    # 3种转化方法
    # examples using a.item()
    type(np.float32(0).item()) # <type 'float'>
    type(np.float64(0).item()) # <type 'float'>
    type(np.uint32(0).item())  # <type 'long'>
    # examples using np.asscalar(a)
    type(np.asscalar(np.int16(0)))   # <type 'int'>
    type(np.asscalar(np.cfloat(0)))  # <type 'complex'>
    type(np.asscalar(np.datetime64(0, 'D')))  # <type 'datetime.datetime'>
    type(np.asscalar(np.timedelta64(0, 'D'))) # <type 'datetime.timedelta'>
    # 强制转化
    int(np.int64(0))
    
  • References

  1. python中的常见错误
发布了857 篇原创文章 · 获赞 1291 · 访问量 92万+

猜你喜欢

转载自blog.csdn.net/The_Time_Runner/article/details/105353431
今日推荐