gpt4 book ai didi

python - 将 Pandas 系列导出为 JSON - numpy 类型错误

转载 作者:太空宇宙 更新时间:2023-11-03 13:19:41 26 4
gpt4 key购买 nike

我想将一些行从 Pandas DataFrame 导出到 JSON。但是,在导出列时出现错误:

TypeError: False is not JSON serializable

TypeError: 0 is not JSON serializable

我查看了我的数据,numpy.int64numpy.bool_ 出现了问题(numpy.float64 工作正常)。

例如,出现以下问题:

import pandas as pd
import simplejson as json

df = pd.DataFrame([[False,0],[True,1]], columns=['a','b'])
json.dumps(df.ix[0].to_dict())

(dict(df.ix[0]) 也会发生同样的事情)。

是否有将 Pandas 系列导出为 JSON 的简单解决方法?

或者至少,一个将任何 numpy 类型强制转换为与 JSON 兼容的最接近类型的函数?

最佳答案

DataFrame 有一个将自身导出为 json 字符串的方法:

>>> df.to_json()
'{"a":{"0":false,"1":true},"b":{"0":0,"1":1}}'

您也可以将其直接导出到文件:

>>> df.to_json(filename)

关于python - 将 Pandas 系列导出为 JSON - numpy 类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18599270/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com