如何使用Python绘制时间序列图? 由于在数据集中,时间分为年份和期间(类似于M1,M2的月份)。
我正在使用matplotlib,但不知道如何分时。
我为获取数据而编写的代码: 将熊猫作为pd导入 从熊猫导入DataFrame data1 = pd.read_csv('CUUR0000SA0.txt',标头=无) data2 = pd.read_csv('SUUR0000SA0.txt',标头=无) 数据= pd.concat([数据1,数据2]) data.columns = [“ a”] 数据= DataFrame(数据) 打印(data.head())
但是,输出数据帧只有一列。
部分数据集如下:
+-------------+------+--------+---------+-----------+
| series id | year | period | value | footnotes |
+-------------+------+--------+---------+-----------+
| CUUR0000SA0 | 2014 | M12 | 234.812 | |
| CUUR0000SA0 | 2014 | M11 | 236.151 | |
| CUUR0000SA0 | 2014 | M10 | 237.433 | |
| CUUR0000SA0 | 2014 | M09 | 238.031 | |
| CUUR0000SA0 | 2014 | M08 | 237.852 | |
图表应根据时间段使用图形解释值的趋势。但是我不知道如何首先将其转换为正确的格式。
答案 0 :(得分:0)
以下是获得解决方案的步骤:
这是代码:
import pandas as pd
from datetime import datetime
df = {0: {"series id":"CUUR0000SA0", "year":2014, "period":"M12", "value":234.812},
1: {"series id":"CUUR0000SA0", "year":2014, "period":"M11", "value":236.151},
2: {"series id":"CUUR0000SA0", "year":2014, "period":"M10", "value":237.433},
3: {"series id":"CUUR0000SA0", "year":2014, "period":"M09", "value":238.031},
4: {"series id":"CUUR0000SA0", "year":2014, "period":"M08", "value":237.852},
}
d = {'M01':1,
'M02':2,
'M02':3,
'M04':4,
'M05':5,
'M06':6,
'M07':7,
'M08':8,
'M09':9,
'M10':10,
'M11':11,
'M12':12,}
df = pd.DataFrame.from_dict(df, orient="index")
df.period = df.period.map(d)
df['date'] = pd.to_datetime(df.year.astype(str) + '/' + df.period.astype(str) + '/01')
df.plot(x='date', y='value')