python - 在 Pandas 中绘图的日期采样/平均

标签 python matplotlib pandas

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

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

理想情况下,我想指定绘图中包含多少天(从开始到结束),可以通过从我的数据帧中获取 Pandas 子样本,也可以通过每 N 天进行平均。

enter image description here

最佳答案

我认为您可以简单地使用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

关于python - 在 Pandas 中绘图的日期采样/平均,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23922014/

相关文章:

python-2.7 - 根据列名堆叠在 Pandas 数据框中

Python检查集合列表是否包含项目

python - 在 Python 中解析字符串列表的有效方法是什么?

python - 我如何处理我的 antlr 语法和目标语言之间的函数名称冲突

至少有 4 位数字的 Python 正则表达式

python - 如何在 Python Seaborn 的线图中的每个标记上添加值/标签?

python - 标题和绘图 matplotlib 之间的巨大空间

python - 无法重置轴

python - 根据具有相同索引/列名称的另一个 DataFrame 中的值设置 Pandas DataFrame 中的单元格值

python - 将超过一百万个 .txt 文件存储到 pandas 数据框中