我认为这是因为索引是一个与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}}'

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐