mbi*_*nov 2 python pandas plotly
我一直在尝试绘制resampled来自 Pandas 数据框的简单数据。这是我的初始代码:
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})
Run Code Online (Sandbox Code Playgroud)
当我这样做时,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
Run Code Online (Sandbox Code Playgroud)
我可以轻松绘制它(下例图中的红线)。然而,当我尝试创建一个额外的数据层(它是值/日期关系的下采样版本)时,问题就开始了,就像每 5 天跳过一次然后绘制它一样。
为此,我使用以下命令创建数据框的样本副本:
df_sampled = df.set_index('date').resample('5D').mean()
Run Code Online (Sandbox Code Playgroud)
当我这样做时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
Run Code Online (Sandbox Code Playgroud)
在那之后,我真的无法再绘制这个了,该列似乎已损坏。随着情节:
x = df_sampled['date'],
y = df_sampled['value'],
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
File "interpolation.py", line 36, in <module>
x = df_sampled['date'],
...
KeyError: 'date'
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题。基本上,我正在尝试创建这个图像。红线是我的原始数据,蓝线是下采样和平滑的版本。
- - 更新 - -
下面提供的答案有效,我得到以下结果:
date不是列,而是index,所以需要:
x = df_sampled.index
y = df_sampled['value']
Run Code Online (Sandbox Code Playgroud)
index或者从by创建列reset_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']
Run Code Online (Sandbox Code Playgroud)