You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Pandas读取JSON时将索引设为float而非DatetimeIndex?

解决方法

当你用pd.read_json()读取这个JSON文件时,Pandas默认会尝试将索引列中看起来像日期的字符串自动解析为DatetimeIndex——这里的"69.0"、"70.0"这类字符串被误判为年份格式了。要保留并转换为float类型索引,你可以按以下步骤操作:

步骤1:禁用自动日期解析

读取JSON时,添加convert_dates=False参数,阻止Pandas将索引解析为日期:

import pandas as pd

df = pd.read_json("df.json", convert_dates=False)

此时DataFrame的索引是字符串类型(比如"69.0"),而非日期索引。

步骤2:将索引转换为float类型

接下来把字符串索引强制转换为float:

df.index = df.index.astype(float)

现在你检查df.index.dtype会发现是float64,df.tail()返回的索引也会是你期望的float格式了。

另一种更简洁的写法

你也可以把两步合并成一行:

df = pd.read_json("df.json", convert_dates=False).rename(index=float)

rename(index=float)会直接把索引转换为float类型,效果和astype(float)一致。


内容的提问来源于stack exchange,提问作者itai ariel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:36:59