【问题标题】:rolling mean in Pandas with fixed time window (instead of fixed nb. of observations)具有固定时间窗口的 Pandas 中的滚动平均值(而不是固定的观察值)
【发布时间】:2016-05-01 03:56:35
【问题描述】:

我有一个包含两列和一个 3 级索引结构的数据框。列是价格和交易量,指数是交易者 - 股票 - 日。

我想计算我数据中每个交易者 - 股票组合在过去 50 天内价格和交易量的滚动平均值。

这是我目前想出的。

test=test.set_index(['date','trader', 'stock'])

test=test.unstack().unstack()

test=test.resample("1D")

test=test.fillna(0)

test[[col+'_norm' for col in test.columns]]=test.apply(lambda x: pd.rolling_mean(x,50,50))

test.stack().stack().reset_index().set_index(['trader', '库存','日期']).sort_index().head()

也就是说,我将我的数据集拆开两次,这样我就只剩下时间轴了,我可以计算我的变量的 50 天滚动平均值,因为 50 次观察将对应于 50 天(在重新采样数据之后)。

问题是我不知道如何为我的滚动平均变量创建正确的名称

test[[col+'_norm' for col in test.columns]]

TypeError:只能将元组(不是“str”)连接到元组

有什么想法吗?我的算法实际上是否正确以获得这些滚动方式? 非常感谢!

【问题讨论】:

    标签: python pandas indexing


    【解决方案1】:

    pd.rolling_mean 的结果(带有修改的列名)可以与原始 DataFrame 连接:

    means = pd.rolling_mean(test, 50, 50)
    means.columns = [('{}_norm'.format(col[0]),)+col[1:] for col in means.columns]
    test = pd.concat([test, means], axis=1)
    

    import numpy as np
    import pandas as pd
    
    N = 10
    test = pd.DataFrame(np.random.randint(4, size=(N, 3)),
                        columns=['trader', 'stock', 'foo'],
                        index=pd.date_range('2000-1-1', periods=N))
    test.index.names = ['date']
    test = test.set_index(['trader', 'stock'], append=True)
    
    test = test.unstack().unstack()
    
    test = test.resample("1D")
    
    test = test.fillna(0)
    
    means = pd.rolling_mean(test, 50, 50)
    means.columns = [('{}_norm'.format(col[0]),)+col[1:] for col in means.columns]
    test = pd.concat([test, means], axis=1)
    
    test = test.stack().stack()
    test = test.reorder_levels(['trader', 'stock', 'date'])
    test = test.sort_index()
    print(test.head())
    

    产量

                             foo  foo_norm
    trader stock date                     
    0      0     2000-01-01    0       NaN
                 2000-01-02    0       NaN
                 2000-01-03    0       NaN
                 2000-01-04    0       NaN
                 2000-01-05    0       NaN
    ...
    

    【讨论】:

    • 那太好了@unutbu!你说滚动平均值必须为每一列调用一次,因为我在列中有一个多索引,对吗?事实上,我似乎可以在整个数据帧上调用滚动平均值
    • 其实我写的是一个错误。由于您可以在整个 DataFrame 上调用 pd.rolling_mean,因此最好这样做。然后,我们可以通过将滚动平均 DataFrame 与test 连接来获得所需的结果。我已经编辑了帖子以说明我的意思。
    • 完美谢谢!你能解释一下你在这里实际在做什么吗means.columns = [('{}_norm'.format(col[0]),)+col[1:] for col in means.columns]。看来你是在重组三个索引级别?
    • means.columns 是一个多索引。因此,当您迭代means.columns 时,col 被分配给像('foo',1,2) 这样的三元组,其中12 指的是traderstock。将_norm 附加到foo 似乎更有意义。所以'{}_norm'.format(col[0]) 用于形成字符串foo_norm。因此('{}_norm'.format(col[0]),)+col[1:] 添加了像('foo_norm',)+(1,2) 这样等于('foo_norm',1,2) 的元组。所以这条大线的目的只是将列元组(如('foo',1,2))更改为('foo_norm',1,2)
    猜你喜欢
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 2021-08-13
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 2014-11-03
    相关资源
    最近更新 更多