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

使用Pandas DataReader导入世行数据后绘图x轴年份异常如何解决

问题根因

pandas_datareader的世界银行接口wb.download()返回的数据集默认使用[国家, 年份]作为双层复合索引,其中年份字段为字符串类型,且数据默认按年份倒序排列。直接调用df.plot()时,pandas无法识别复合索引中的年份为时间轴,因此会出现x轴显示异常的问题。

修复方案

方案1:指定x轴参数绘图(最简单)

不需要修改原数据结构,重置索引后直接指定x轴字段即可:

from pandas_datareader import wb
ind = ['NY.GNP.PCAP.CD']
# 下载数据
df = wb.download(indicator=ind, country='CHN', start=2000, end=2021)
# 重置索引,把复合索引中的国家、年份转为普通列
df = df.reset_index()
# 将年份转为数值类型,保证排序正确
df['year'] = df['year'].astype(int)
# 绘图时显式指定x、y轴
df.plot(x='year', y='NY.GNP.PCAP.CD', xlabel='年份', ylabel='人均GNP(美元)')

方案2:设置时间索引(适合后续时间序列操作)

如果需要对数据做时间序列相关的后续计算,可以调整索引为时间格式:

from pandas_datareader import wb
import pandas as pd
ind = ['NY.GNP.PCAP.CD']
df = wb.download(indicator=ind, country='CHN', start=2000, end=2021)
df = df.reset_index()
# 将年份转为datetime格式并设为索引
df.index = pd.to_datetime(df['year'], format='%Y')
# 按时间正序排列
df = df.sort_index()
df.plot(y='NY.GNP.PCAP.CD', xlabel='年份')

两种方案都可以正常显示x轴的年份刻度,按自己的使用场景选择即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 16:54:02