拆分子批次的groupby结果

2024-09-30 22:17:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧,stock_data.head()

       date     open    high    low     close    volume    Name
0   2013-02-08  15.07   15.12   14.63   14.75   8407500     AAL
1   2013-02-11  14.89   15.01   14.26   14.46   8882000     AAL
2   2013-02-12  14.45   14.51   14.10   14.27   8126000     AAL
3   2013-02-13  14.30   14.94   14.25   14.66   10259500    AAL
4   2013-02-14  14.94   14.96   13.16   13.99   31879900    AAL

下面是一段代码,用于从数据帧生成groupby命令:

avg_permonth = stock_data.set_index('date').groupby(pd.Grouper(freq='M'))
avg_permonth['volume'].mean()


date
2013-02-28    5.261789e+06
2013-03-31    4.825485e+06
2013-04-30    4.990292e+06
2013-05-31    4.836257e+06
2013-06-30    5.145598e+06
                  ...     
2017-10-31    3.903486e+06
2017-11-30    4.133801e+06
2017-12-31    3.919748e+06
2018-01-31    4.486669e+06
2018-02-28    6.249305e+06
Freq: M, Name: volume, Length: 61, dtype: float64

我的问题是,如何将这些结果按年份分割,然后创建date vs volume的子批次?(我必须先reset_index()还是可以把index画成x axis?)我希望5subplots2013-022018-02

我尝试了这个this SO post,但没有给出我想要的结果-它是5个子地块,但每个地块的x axis都是从2013年到2018年,并且都有相同的地块

我希望第一个子地块上的x axis是从2013年的第一个日期值到2013年的最后一个日期值,2014年的第二个地块,依此类推


Tags: 数据namedatadateindexstockopenhead
1条回答
网友
1楼 · 发布于 2024-09-30 22:17:46

您可以这样做:

import matplotlib.pyplot as plt

# dummy values like your serie
s = pd.Series(range(12*6), 
              index=pd.date_range('2013-01-01', '2018-12-31', freq='M'), 
              name='volume')

# Create figure and axs for multiple Axes
fig, axs = plt.subplots(3, 2, figsize=(12,12))

# groupby year to plot each year un a subplot
for i, (year, sg) in enumerate(s.groupby(s.index.year)):
    # plot each year in a subplot
    sg.plot(ax=axs[i//2, i%2]) # here you can add several parameters for colors and stuff
    # or axs[i//2, i%2].plot(sg.index, sg.values) would give the same result
plt.show() 

相关问题 更多 >