【发布时间】:2014-05-30 11:22:29
【问题描述】:
有没有办法在 Pandas 中指定X 轴的采样率?特别是,当这个轴包含datetime 对象时?例如
df['created_dt'][0]
datetime.date(2014, 3, 24)
理想情况下,我想指定要在绘图中包含多少天(从开始到结束),方法是从我的数据框中获取 Pandas 子样本,或者通过平均每 N 天。
【问题讨论】:
标签: python matplotlib pandas
有没有办法在 Pandas 中指定X 轴的采样率?特别是,当这个轴包含datetime 对象时?例如
df['created_dt'][0]
datetime.date(2014, 3, 24)
理想情况下,我想指定要在绘图中包含多少天(从开始到结束),方法是从我的数据框中获取 Pandas 子样本,或者通过平均每 N 天。
【问题讨论】:
标签: python matplotlib pandas
我认为您可以简单地使用groupby 和cut 将数据分组为时间间隔。在此示例中,原始数据框有 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()
【讨论】: