Python 3.x 划分每年的时间序列以进行绘图
我想画一个时间序列,从2015年10月开始,到2018年2月结束,在一个图表中,每年都是一条直线。时间序列是Python 3.x 划分每年的时间序列以进行绘图,python-3.x,pandas,time-series,Python 3.x,Pandas,Time Series,我想画一个时间序列,从2015年10月开始,到2018年2月结束,在一个图表中,每年都是一条直线。时间序列是int64值,并且位于数据帧中。日期作为数据框中的一列出现在datetime64[ns]中 我如何从Jan Dez创建一个每年有4行的图表 使用图['share_price']和图['date']。我试过石斑鱼,但不知怎么的,它取了2015年10月的值,并与其他年份的1月值混合 这个groupby接近我想要的,但是我丢失了列表索引所属年份的信息 graph.groupby('date').
int64
值,并且位于数据帧中。日期作为数据框中的一列出现在datetime64[ns]
中
我如何从Jan Dez创建一个每年有4行的图表
使用图['share_price']和图['date']。我试过石斑鱼,但不知怎么的,它取了2015年10月的值,并与其他年份的1月值混合
这个groupby接近我想要的,但是我丢失了列表索引所属年份的信息
graph.groupby('date').agg({'share_price':lambda x: list(x)})
然后我创建了一个数据框架,其中有4列,每年1列,但我仍然不知道如何将这4列进行分组,以便能够以我想要的方式绘制图形。您可以通过以下方式实现这一点:
>>> import pandas as pd
>>> import numpy as np
>>> index = pd.date_range('2015-10-01', '2018-02-28')
>>> values = np.random.randint(-3, 4, len(index)).cumsum()
>>> df = pd.DataFrame({
... 'date': index,
... 'share_price': values
>>> })
>>> df.head()
date share_price
0 2015-10-01 0
1 2015-10-02 3
2 2015-10-03 2
3 2015-10-04 5
4 2015-10-05 4
>>> df.set_index('date').plot()
您可以按如下方式转换数据帧:
>>> df['year'] = df.date.dt.year
>>> df['date'] = df.date.dt.strftime('%m-%d')
>>> unstacked = df.set_index(['year', 'date']).share_price.unstack(-2)
>>> unstacked.head()
year 2015 2016 2017 2018
date
01-01 NaN 28.0 -16.0 21.0
01-02 NaN 29.0 -14.0 22.0
01-03 NaN 29.0 -16.0 22.0
01-04 NaN 26.0 -15.0 23.0
01-05 NaN 25.0 -16.0 21.0
然后正常绘制:
unstacked.plot()
您可以通过以下方式实现:
>>> import pandas as pd
>>> import numpy as np
>>> index = pd.date_range('2015-10-01', '2018-02-28')
>>> values = np.random.randint(-3, 4, len(index)).cumsum()
>>> df = pd.DataFrame({
... 'date': index,
... 'share_price': values
>>> })
>>> df.head()
date share_price
0 2015-10-01 0
1 2015-10-02 3
2 2015-10-03 2
3 2015-10-04 5
4 2015-10-05 4
>>> df.set_index('date').plot()
您可以按如下方式转换数据帧:
>>> df['year'] = df.date.dt.year
>>> df['date'] = df.date.dt.strftime('%m-%d')
>>> unstacked = df.set_index(['year', 'date']).share_price.unstack(-2)
>>> unstacked.head()
year 2015 2016 2017 2018
date
01-01 NaN 28.0 -16.0 21.0
01-02 NaN 29.0 -14.0 22.0
01-03 NaN 29.0 -16.0 22.0
01-04 NaN 26.0 -15.0 23.0
01-05 NaN 25.0 -16.0 21.0
然后正常绘制:
unstacked.plot()