首页 > 解决方案 > pandas to_json 更改数据框的索引类型

问题描述

我正在读取一个 CSV 文件并将其转换为数据帧,然后转换为 json,以便通过 api 发送它。

问题是在读取 json 并将其重新转换为数据帧后,索引类型更改Int64IndexIndex

这是我发送我的 DF 的方法:

df=pd.read_csv('/tmp/'+file, sep=urllib.parse.unquote(sep), encoding=encoding, dtype=dt, decimal=decimal)
# Here, df.Index gives Index(['1', '2', '3', '4', '5', '6', '7', '8', '9'], dtype='object', name='Code')
return {
            'statusCode': 200,
            'body': df.to_json()
        }

然后我收到它:

x=pd.read_json((json.dumps(json.loads(r.text)))) # r is the body from first part
# And here x.Index gets transformed to Int64Index([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype='int64', name='Code')

标签: pythonjsonpandas

解决方案


要将索引映射回字符串,您可以使用

df.index = df.index.map( str )

推荐阅读