python - pandas to_json 更改数据框的索引类型
问题描述
我正在读取一个 CSV 文件并将其转换为数据帧,然后转换为 json,以便通过 api 发送它。
问题是在读取 json 并将其重新转换为数据帧后,索引类型更改Int64Index
为Index
这是我发送我的 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')
解决方案
要将索引映射回字符串,您可以使用
df.index = df.index.map( str )
推荐阅读
- python - Python字典理解包含在另一个字典中找不到的项目列表
- javascript - 如何通过单击导航栏(单站点页面)中的链接来关闭导航栏?
- gitlab - Gitlab 页面上的 SSG NextJS 卡在 404 上?
- hyper-v - 由于“序列不包含元素”,Docker for Windows 无法启动
- java - 如何更改单个 RecyclerView 行的 ImageView 可绘制对象
- watchkit - 如何在手表应用程序中添加页面控件
- python - python3 tkinter和matplot冲突
- angular - Ionic 动态显示选项卡图标 Angular
- c++ - 如何使用 GTest 测试命令行选项解析器
- linux - Linux Huge pages 内存使用计算