问题| Pandas获取数据转json时报错 TypeError: Object of type int64 is not JSON serializable @Python

问题描述

背景:

  • 在 windows 系统的 PyCharm 中(Python3环境),使用 Pandas 的 read_excel 方法获取 excel 表格中的数据,经过处理后,将数据转为 json 时失败,报错如下:
Traceback (most recent call last):
  File "D:\All_Projects\AIProject\pythonProject_ben_clustering\jun_01-20220901-clustering\caogao2.py", line 22, in <module>
    json_str = json.dumps(datas,
  File "D:\AllApp\Miniconda3\lib\json\__init__.py", line 234, in dumps
    return cls(
  File "D:\AllApp\Miniconda3\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "D:\AllApp\Miniconda3\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "D:\AllApp\Miniconda3\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type int64 is not JSON serializable

具体:

  • 需求:获取表格中的数据,并将处理好的数据转为 json 格式(编码)后,写入到 .json 文件中
import pandas as pd
import json

# 读入Excel文件,获取数据
data = pd.read_excel('caogao.xlsx',  # 打开excel表所在路径
                     sheet_name='Sheet2',  # 读取指定的工作表
                     header=0,  # 使用第一行数据作为列索引(默认)—— 该参数可选
                     )

datas = []
for i in data.index:  # 行索引
    students = list(data.iloc[i, :])  # 获取每行数据,并转为列表形式
    datas.append(students)
print("datas:", datas)


# 写数据
with open('caogao.json', 'w', encoding="utf8") as new_f:
    json_str = json.dumps(datas,
                          ensure_ascii=False)  # 编码
    new_f.write(json_str + '\n')  # 一行一行写入,加\n换行显示

报错

解决方法

分析:

  • 通过测试发现:表格中的数字,被 Pandas 转成 int64,但 json 库无法识别(python3 的所有整形是 int)。
  • 解决方法:需要将 int64 这种数据类型转换成 python3 内置数据类型,如:int、float、str 字符串类型等

测试

处理:

  • 针对个人需求及解决方法,在此次的处理中,将数据类型(主要是数据中的数字)转为 str 格式后,再进行 json.dumps 编码
import pandas as pd
import json

# 读入Excel文件,获取数据
data = pd.read_excel('caogao.xlsx',  # 打开excel表所在路径
                     sheet_name='Sheet2',  # 读取指定的工作表
                     header=0,  # 使用第一行数据作为列索引(默认)—— 该参数可选
                     )

datas = []
for i in data.index:  # 行索引
    students = list(data.iloc[i, :])  # 获取每行数据,并转为列表形式
    students = [str(x) for x in students]  # 将每个元素转为字符串形式,否则可能:TypeError: Object of type int64 is not JSON serializable
    datas.append(students)
print("datas:", datas)


# 写数据
with open('caogao.json', 'w', encoding="utf8") as new_f:
    json_str = json.dumps(datas,
                          ensure_ascii=False)  # 编码
    new_f.write(json_str + '\n')  # 一行一行写入,加\n换行显示

结果
成功写入

参考1:https://blog.csdn.net/qq_29592829/article/details/100162574
参考2:https://blog.csdn.net/weixin_39561473/article/details/123227500

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值