【问题标题】:Unable to resample then plot a Pandas Data Frame无法重新采样然后绘制 Pandas 数据框
【发布时间】:2017-10-29 00:56:15
【问题描述】:

我一直在尝试绘制来自 Pandas 数据框的简单 resampled 数据。这是我的初始代码:

import pandas as pd
import numpy as np
from datetime import datetime, timedelta

# Extra plotly bits
import plotly
import plotly.plotly as py
import plotly.graph_objs as go

date_today = datetime.now()
days = pd.date_range(date_today, date_today + timedelta(56), freq='D')

np.random.seed(seed=1111)
data = np.random.randint(1, high=100, size=len(days))
df = pd.DataFrame({'date': days, 'value': data})

当我print df 时,我得到了这个:

                         date  value
0  2017-10-28 17:13:23.867396     29
1  2017-10-29 17:13:23.867396     56
2  2017-10-30 17:13:23.867396     82
3  2017-10-31 17:13:23.867396     13
4  2017-11-01 17:13:23.867396     35
5  2017-11-02 17:13:23.867396     53
6  2017-11-03 17:13:23.867396     25
7  2017-11-04 17:13:23.867396     23
8  2017-11-05 17:13:23.867396     21
9  2017-11-06 17:13:23.867396     12
10 2017-11-07 17:13:23.867396     15
...
48 2017-12-15 17:13:23.867396      1
49 2017-12-16 17:13:23.867396     88
50 2017-12-17 17:13:23.867396     94
51 2017-12-18 17:13:23.867396     48
52 2017-12-19 17:13:23.867396     26
53 2017-12-20 17:13:23.867396     65
54 2017-12-21 17:13:23.867396     53
55 2017-12-22 17:13:23.867396     54
56 2017-12-23 17:13:23.867396     76

我可以很容易地画出这个(下图示例中的红线)。但是,当我尝试创建一个额外的数据层时,问题就开始了,它是值/日期关系的下采样版本,例如每 5 天跳过一次然后绘制它。

为此,我创建了我的数据框的样本副本:

df_sampled = df.set_index('date').resample('5D').mean()

当我执行print df_sampled 时,我得到:

                            value
date
2017-10-28 17:32:39.622881   43.0
2017-11-02 17:32:39.622881   26.8
2017-11-07 17:32:39.622881   26.6
2017-11-12 17:32:39.622881   59.4
2017-11-17 17:32:39.622881   66.8
2017-11-22 17:32:39.622881   33.6
2017-11-27 17:32:39.622881   27.8
2017-12-02 17:32:39.622881   64.4
2017-12-07 17:32:39.622881   43.2
2017-12-12 17:32:39.622881   64.4
2017-12-17 17:32:39.622881   57.2
2017-12-22 17:32:39.622881   65.0

在那之后,我再也无法真正绘制这个了,该列似乎已损坏。随着情节:

    x = df_sampled['date'],
    y = df_sampled['value'],

我收到此错误:

File "interpolation.py", line 36, in <module>
    x = df_sampled['date'],
...
KeyError: 'date'

我该如何解决这个问题。基本上,我正在尝试创建此图像。红线是我的原始数据,蓝线是下采样和平滑的版本。

--- 更新 ---

下面提供的答案有效,我得到以下结果:

【问题讨论】:

    标签: python pandas plotly


    【解决方案1】:

    date不是列,而是index,所以需要:

    x = df_sampled.index
    y = df_sampled['value']
    

    或从indexreset_index 创建列:

    df_sampled = df.set_index('date').resample('5D').mean().reset_index()
    #alternative
    #df_sampled = df.resample('5D', on='date').mean().reset_index()
    
    x = df_sampled['date']
    y = df_sampled['value']
    

    【讨论】:

      猜你喜欢
      • 2016-11-02
      • 2019-04-15
      • 2017-09-19
      • 2014-10-04
      • 2013-01-13
      • 2019-06-14
      • 1970-01-01
      • 2019-02-03
      • 2016-04-12
      相关资源
      最近更新 更多