Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.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 为每个ID单独设置滚动和窗口_Python_Python 3.x_Python 2.7_Pandas_Dataframe - Fatal编程技术网

Python 为每个ID单独设置滚动和窗口

Python 为每个ID单独设置滚动和窗口,python,python-3.x,python-2.7,pandas,dataframe,Python,Python 3.x,Python 2.7,Pandas,Dataframe,在下面的数据帧中,我需要每个ID的最后两个“时间”周期的滚动和X df = pd.DataFrame({'ID':[1000, 1000, 1000, 2000, 2000, 2000, 3000,3000,3000], 'Time':[1,2,3,1,2,3,1,2,3], 'X':[101, 201, 123, 234, 222, 333, 444, 0, 0 ]}) 我尝试了以下代码,但结果是滚动总和从客户ID“1000”结转到了“

在下面的数据帧中,我需要每个ID的最后两个“时间”周期的滚动和X

df = pd.DataFrame({'ID':[1000, 1000, 1000, 2000, 2000, 2000, 3000,3000,3000],
              'Time':[1,2,3,1,2,3,1,2,3],
              'X':[101, 201, 123, 234, 222, 333, 444, 0, 0 ]})
我尝试了以下代码,但结果是滚动总和从客户ID“1000”结转到了“2000”,依此类推

df[['X']].rolling(2).sum()
IIUC:

In [190]: df['new'] = df.groupby('ID', as_index=False)['X'].rolling(2).sum().reset_index(level=0, drop=True)

In [191]: df
Out[191]:
     ID  Time    X    new
0  1000     1  101    NaN
1  1000     2  201  302.0
2  1000     3  123  324.0
3  2000     1  234    NaN
4  2000     2  222  456.0
5  2000     3  333  555.0
6  3000     1  444    NaN
7  3000     2    0  444.0
8  3000     3    0    0.0