生成隨機數的時間序列,然後下采樣
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# I want 7 days of 24 hours with 60 minutes each
periods = 7 * 24 * 60
tidx = pd.date_range('2016-07-01', periods=periods, freq='T')
# ^ ^
# | |
# Start Date Frequency Code for Minute
# This should get me 7 Days worth of minutes in a datetimeindex
# Generate random data with numpy. We'll seed the random
# number generator so that others can see the same results.
# Otherwise, you don't have to seed it.
np.random.seed([3,1415])
# This will pick a number of normally distributed random numbers
# where the number is specified by periods
data = np.random.randn(periods)
ts = pd.Series(data=data, index=tidx, name='HelloTimeSeries')
ts.describe()
count 10080.000000
mean -0.008853
std 0.995411
min -3.936794
25% -0.683442
50% 0.002640
75% 0.654986
max 3.906053
Name: HelloTimeSeries, dtype: float64
我們將每分鐘 7 天的資料和每 15 分鐘的樣本數量下調一次。所有頻率程式碼都可以在這裡找到。
# resample says to group by every 15 minutes. But now we need
# to specify what to do within those 15 minute chunks.
# We could take the last value.
ts.resample('15T').last()
或者我們可以對 groupby
物件做任何其他事情,文件 。
我們甚至可以聚合幾個有用的東西。讓我們繪製這個 resample('15M')
資料的 min
,mean
和 max
。
ts.resample('15T').agg(['min', 'mean', 'max']).plot()
讓我們重新審視'15T'
(15 分鐘),'30T'
(半小時)和'1H'
(1 小時),看看我們的資料如何變得更加平滑。
fig, axes = plt.subplots(1, 3, figsize=(12, 4))
for i, freq in enumerate(['15T', '30T', '1H']):
ts.resample(freq).agg(['max', 'mean', 'min']).plot(ax=axes[i], title=freq)