【问题标题】:Pandas groupby ewmPandas group来自 ewm
【发布时间】:2020-01-19 23:53:35
【问题描述】:

我已经标记了事件(时间序列)数据,其中事件以给定标签的随机间隔发生。我想计算组内 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())

感谢SO: Pandas Groupby and apply method with custom function),我能够计算分组的 EWMA:

ewm = ts.groupby(['C1']).apply(lambda x: x['X1'].ewm(halflife=10).mean())
ewm.head()

它产生一个系列,由一个分类变量和日期时间索引。系列的长度与原始数据帧和时间序列(df和ts)相同

现在我想我可以做一些体操,通过加入行索引(假设排序顺序没有改变)将它重新连接到原始数据帧 (df),但这似乎不正确,甚至可能是一种冒险的方法,因为 groupby 仅在一个分类标签中-我需要小心并进行一些检查/排序/重新索引。

似乎应该有一种更简单的方法可以将时间序列列直接添加到数据框 (df) 或时间序列 (ts) 中,而无需创建单独的系列或数据框并将它们连接起来。如果我想添加滚动统计信息也是如此,例如:

ts.groupby('C1').rolling(10).mean()

提前感谢您的任何帮助或意见。

结果基于接受的答案:

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)

【问题讨论】:

    标签: python pandas time-series pandas-groupby rolling-computation


    【解决方案1】:

    你可以试试这个吗? 不要设置ts = df.set_index('T')。然后你可以做如下

    ts['ewm']=ts.groupby(['C1'], sort=False).apply(lambda x: x['X1'].ewm(halflife=10).mean()).reset_index(drop=True)
    

    【讨论】:

    • 感谢您的回答,但是,在绘制数据后,EWMA 似乎没有在组内正确应用。这只有在绘制数据后才明显。
    【解决方案2】:

    让我们解决问题,使用transform:

    t['ewm'] = ts.groupby(['C1'])['X1'].transform(lambda x: x.ewm(halflife=10).mean()).values()
    

    【讨论】:

    • 谢谢。我完全忘记了 groupby().transform()!您的解决方案有效,并且 ewma 数据与原始系列正确对齐。在数据中添加了一些异常值,并用 altair 绘制以显示结果符合预期。将编辑我的 OP 以显示结果。
    • @RandallGoodwin What should I do when someone answers my question? 人们倾向于花大量时间彻底回答问题。如果某个解决方案回答了您的问题,请检查一下,如果没有解决问题,请发表评论。
    • @Trenton_M。感谢您的提醒。我投了赞成票,但没有点击支票接受它。现在就这样做了。
    • 太棒了!我可以补充一下“df.values 不是一个函数,所以你不需要调用它。只需使用 df.values 而不是 df.values()”按照这个答案stackoverflow.com/a/46317362
    猜你喜欢
    • 2016-10-21
    • 1970-01-01
    • 2021-02-10
    • 2012-05-04
    • 2020-01-20
    • 2020-11-02
    • 1970-01-01
    • 2018-03-05
    • 2021-07-08
    相关资源
    最近更新 更多