Ran*_*win 5 python time-series pandas rolling-computation pandas-groupby
我已经标记了事件(时间序列)数据,其中事件以给定标签的随机间隔发生。我想计算组内 ewma 并将其作为新列“X1_EWMA”添加到数据框中。这是到目前为止的代码:
import pandas as pd
import numpy as np
import altair as alt
n = 1000
df = pd.DataFrame({
'T': pd.date_range('20190101', periods=n, freq='H'),
'C1': np.random.choice(list('PYTHON'), n),
'C2': np.random.choice(list('FUN'), n),
'X1': np.random.randn(n),
'X2': 100 + 10 * np.random.randn(n)
})
ts = df.set_index('T')
display(df.head())
display(ts.head())
Run Code Online (Sandbox Code Playgroud)
感谢SO:Pandas Groupby 和带有自定义函数的应用方法),我能够使用以下方法计算分组的 EWMA:
ewm = ts.groupby(['C1']).apply(lambda x: x['X1'].ewm(halflife=10).mean())
ewm.head()
Run Code Online (Sandbox Code Playgroud)
它产生一个系列,由一个分类变量和日期时间索引。系列的长度与原始数据帧和时间系列(df 和 ts)相同
现在我想我可以做一些体操,通过加入行索引(假设排序顺序没有改变)来将它重新连接到原始数据框(df),但这似乎不对,甚至可能是一种冒险的方法,因为 groupby 仅在分类标签之一内 - 我需要小心并进行一些检查/排序/重新索引。
似乎应该有一种更简单的方法将时间序列列直接添加到数据帧 (df) 或时间序列 (ts),而无需创建单独的序列或数据帧并加入它们。如果我想添加滚动统计数据,情况也是如此,例如:
ts.groupby('C1').rolling(10).mean()
Run Code Online (Sandbox Code Playgroud)
在此先感谢您的任何帮助或输入。
结果基于接受的答案:
import pandas as pd
import numpy as np
import math
import altair as alt
alt.renderers.enable('notebook') # for rendering in the notebook
alt.data_transformers.enable('json') # for plotting data larger than 5000 points
# make a dataframe to test
n = 1000
df = pd.DataFrame({
'T': pd.date_range('20190101', periods=n, freq='H'),
'C1': np.random.choice(list('PYTHON'), n),
'C2': np.random.choice(list('FUN'), n),
'X1': np.linspace(0, 2*math.pi, n),
'X2': np.random.randn(n),
})
# add a new variable that is a function of X1, X2 + a random outlier probability
df['X3'] = 0.2 * df['X2'] + np.sin(df['X1']) + np.random.choice(a=[0, 2], size=n, p=[0.98, 0.02])
# make it a time series for later resampling use cases.
ts = df.set_index('T')
# SOLUTION: Add the ewma line with groupby().transform().
ts['ewm'] = ts.groupby(['C1'])['X3'].transform(lambda x: x.ewm(halflife=1).mean())
# plot the points and ewma using altair faceting and layering
points = alt.Chart().mark_circle(size=20, opacity=0.9).encode(
x = 'T',
y = 'X3',
color = 'C2',
).properties(width=270, height=170)
lines = alt.Chart().mark_line(size=1, color='red', opacity=1).encode(
x = 'T',
y = 'ewm'
)
alt.layer(points, lines).facet(facet='C1', data=ts.reset_index()).properties(columns=3)
Run Code Online (Sandbox Code Playgroud)
让我们解决这个问题,使用transform:
t['ewm'] = ts.groupby(['C1'])['X1'].transform(lambda x: x.ewm(halflife=10).mean()).values()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3867 次 |
| 最近记录: |