Skip to main content
 首页 » 编程设计

python如何将数据框中的一列转换为日期类型和绘图

2025年05月04日24cmt

我有一个数据框 df 如下:

df = pd.DataFrame({'date': [20121231,20130102, 20130105, 20130106, 20130107, 20130108],'price': [25, 163, 235, 36, 40, 82]}) 

如何将df['date']设为date type并将'price'设为y-label 和 'date' 作为 x-label?

非常感谢。

请您参考如下方法:

使用to_datetime使用参数 format,检查 http://strftime.org/ :

df['date'] = pd.to_datetime(df['date'], format='%Y%m%d') 
print (df) 
        date  price 
0 2012-12-31     25 
1 2013-01-02    163 
2 2013-01-05    235 
3 2013-01-06     36 
4 2013-01-07     40 
5 2013-01-08     82 

然后 plot :

df.plot(x='date', y='price')