python和pandas有什么关系_为什么32位和64位numpy/pandas之间有区别

这篇博客探讨了在32位和64位Python环境中,numpy和pandas指数之间的差异。作者指出,索引类型的不匹配可能导致问题,如在序列化过程中引发错误。通过将索引类型转换为numpy.int32、numpy.int64或常规Python int,可以解决这类问题。示例代码展示了如何转换索引类型以避免JSON转换时的TypeError。
摘要由CSDN通过智能技术生成

我认为这是因为索引是一个与Pythonint大小不同的numpy.intNN,并且这些索引不是从一个本地转换到另一个索引。在

比如,在我的64位Python 2.7和Numpy上:>>> isinstance(numpy.int64(5), int)

True

>>> isinstance(numpy.int32(5), int)

False

然后:

^{pr2}$

您可以尝试将索引更改为numpy.int32、numpy.int64或{}:>>> df = pd.DataFrame( [ {'a': 1}, {'a': 2} ] )

>>> df.index = df.index.astype(numpy.int32) # perhaps your index was of these?

>>> json.dumps(df.to_dict())

Traceback (most recent call last):

File "", line 1, in

File "/usr/lib/python2.7/json/__init__.py", line 243, in dumps

return _default_encoder.encode(obj)

File "/usr/lib/python2.7/json/encoder.py", line 207, in encode

chunks = self.iterencode(o, _one_shot=True)

File "/usr/lib/python2.7/json/encoder.py", line 270, in iterencode

return _iterencode(o, 0)

TypeError: keys must be a string

因此,您可以尝试将索引类型更改为int32、int64或只是普通Python int:>>> df.index = df.index.astype(numpy.int64)

>>> json.dumps(df.to_dict())

'{"a": {"0": 1, "1": 2}}'

>>> df.index = df.index.astype(int)

>>> json.dumps(df.to_dict())

'{"a": {"0": 1, "1": 2}}'

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值