Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在熊猫多索引数据帧上使用滚动函数_Python_Pandas_Dataframe - Fatal编程技术网

Python 在熊猫多索引数据帧上使用滚动函数

Python 在熊猫多索引数据帧上使用滚动函数,python,pandas,dataframe,Python,Pandas,Dataframe,我在pandas中有一个多索引数据帧,其中索引位于ID和时间戳上。我希望能够计算出每个ID的时间序列滚动和,但我似乎不知道如何在没有循环的情况下完成 content = io.BytesIO("""\ IDs timestamp value 0 2010-10-30 1 0 2010-11-30 2 0 2011-11-30 3 1 2000-01-01 300 1 2007-01-01 33

我在pandas中有一个多索引数据帧,其中索引位于ID和时间戳上。我希望能够计算出每个ID的时间序列滚动和,但我似乎不知道如何在没有循环的情况下完成

content = io.BytesIO("""\
IDs    timestamp     value
0      2010-10-30     1
0      2010-11-30     2
0      2011-11-30     3
1      2000-01-01     300
1      2007-01-01     33
1      2010-01-01     400
2      2000-01-01     11""")
df = pd.read_table(content, header=0, sep='\s+', parse_dates=[1])
df.set_index(['IDs', 'timestamp'], inplace=True)
pd.stats.moments.rolling_sum(df,window=2
这个的输出是:

                value
IDs timestamp
0   2010-10-30    NaN
    2010-11-30      3
    2011-11-30      5
1   2000-01-01    303
    2007-01-01    333
    2010-01-01    433
2   2000-01-01    411
请注意ID 0和1以及1和2在边缘处的重叠(我不希望这样,会弄乱我的计算)。解决这个问题的一种可能方法是在ID上使用groupby,然后循环使用该groupby,然后应用滚动求和


我确信有一个函数可以帮助我在不使用循环的情况下做到这一点

首先分组,然后滚动总和(顶级命名空间中也提供了
滚动总和


似乎pd.rolling\u sum将来会被弃用,因此在此之前,上述答案的更新方法将是:
df.groupby(level='IDs').apply(lambda x:x.rolling(window=2.sum())
updated for pandas>=1.0:
df.groupby(level='IDs',group\u key=False)。rolling(2.sum()
In [18]: df.groupby(level='IDs').apply(lambda x: pd.rolling_sum(x,2))
Out[18]: 
                value
IDs timestamp        
0   2010-10-30    NaN
    2010-11-30      3
    2011-11-30      5
1   2000-01-01    NaN
    2007-01-01    333
    2010-01-01    433
2   2000-01-01    NaN