在熊猫中绘图的日期采样/平均值

时间:2014-05-28 21:15:28

标签: python matplotlib pandas

有没有办法在Pandas中指定X轴的采样率?特别是,当此轴包含datetime个对象?时,例如

df['created_dt'][0]
datetime.date(2014, 3, 24)

理想情况下,我想指定在图表中包含多少天(从开始到结束),或者通过我的数据框中的Pandas子样本,或者平均每N天。

enter image description here

1 个答案:

答案 0 :(得分:1)

我认为您只需使用groupbycut将数据分组为时间间隔即可。在此示例中,原始数据帧有10天,我将日期分为3个时间间隔(即每个80小时)。然后你可以做任何你想做的事情,取平均值,例如:

In [21]:

df=pd.DataFrame(np.random.random((10,3)))
df.index=pd.date_range('1/1/2011', periods=10, freq='D')
print df
                   0         1         2
2011-01-01  0.125353  0.661480  0.849405
2011-01-02  0.551803  0.558052  0.905813
2011-01-03  0.221589  0.070754  0.312004
2011-01-04  0.452728  0.513566  0.535502
2011-01-05  0.730282  0.163804  0.035454
2011-01-06  0.205623  0.194948  0.180352
2011-01-07  0.586136  0.578334  0.454175
2011-01-08  0.103438  0.765212  0.570750
2011-01-09  0.203350  0.778980  0.546947
2011-01-10  0.642401  0.525348  0.500244

[10 rows x 3 columns]

In [22]:

dfgb=df.groupby(pd.cut(df.index.values.astype(float), 3),as_index=False)
df_resample=dfgb.mean()
df_resample.index=dfgb.head(1).index
df_resample.__delitem__(None)
print df_resample
                   0         1         2
2011-01-01  0.337868  0.450963  0.650681
2011-01-05  0.507347  0.312362  0.223327
2011-01-08  0.316396  0.689847  0.539314

[3 rows x 3 columns]

In [23]:

f=plt.figure()
ax0=f.add_subplot(121)
ax1=f.add_subplot(122)
_=df.T.boxplot(ax=ax0)
_=df_resample.T.boxplot(ax=ax1)
_=[item.set_rotation(90) for item in ax0.get_xticklabels()+ax1.get_xticklabels()]
plt.tight_layout()

enter image description here

相关问题