Python 大熊猫翻滚了几天,得到了一笔钱

Python 大熊猫翻滚了几天,得到了一笔钱,python,pandas,dataframe,pandas-groupby,Python,Pandas,Dataframe,Pandas Groupby,这是我的数据帧 d= {'dates': ['2020-07-16','2020-07-15','2020-07-14','2020-07-13','2020-07-16','2020-07-15','2020-07-14','2020-07-13'], 'location':['Paris','Paris','Paris','Paris','NY','NY','NY','NY'],'T':[100,200,300,400,10,20,30,40]} df = pandas.Data

这是我的数据帧

d= {'dates': ['2020-07-16','2020-07-15','2020-07-14','2020-07-13','2020-07-16','2020-07-15','2020-07-14','2020-07-13'], 
    'location':['Paris','Paris','Paris','Paris','NY','NY','NY','NY'],'T':[100,200,300,400,10,20,30,40]} 
df = pandas.DataFrame(data=d)
df['dates']=pandas.to_datetime(df['dates'])
df
我想计算过去2天(包括当前日期)内给定位置的一些
T
值。 这是我想要的熊猫:

    dates   location    T     SUM2D
0   2020-07-16  Paris   100     300
1   2020-07-15  Paris   200     500
2   2020-07-14  Paris   300     700
3   2020-07-13  Paris   400     NaN
4   2020-07-16  NY       10      30
5   2020-07-15  NY       20      50
6   2020-07-14  NY       30      70
7   2020-07-13  NY       4      NaN
我试着玩弄这句话,但没有成功:

df['SUM2D'] = df.set_index('dates').groupby('location').rolling(window=2, freq='D').sum()['T'].values

尝试在索引之前对数据帧进行排序:

df = df.sort_values(['location','dates']).set_index('dates')
df['SUM2D'] = df.groupby('location')['T'].rolling(window=2, freq='D').sum().values

df[::-1]
结果集:

           location    T  SUM2D
dates                          
2020-07-16    Paris  100  300.0
2020-07-15    Paris  200  500.0
2020-07-14    Paris  300  700.0
2020-07-13    Paris  400    NaN
2020-07-16       NY   10   30.0
2020-07-15       NY   20   50.0
2020-07-14       NY   30   70.0
2020-07-13       NY   40    NaN
更紧凑、更优雅的解决方案是使用
变换

df['SUM2D'] = df.sort_values(['dates']).groupby('location')['T'].transform(lambda x: x.rolling(2, 2).sum())
结果是:

       dates location    T  SUM2D
0 2020-07-16    Paris  100  300.0
1 2020-07-15    Paris  200  500.0
2 2020-07-14    Paris  300  700.0
3 2020-07-13    Paris  400    NaN
4 2020-07-16       NY   10   30.0
5 2020-07-15       NY   20   50.0
6 2020-07-14       NY   30   70.0
7 2020-07-13       NY   40    NaN

只需将df[:-1]添加到第一个解决方案中,即可对日期进行重新排序。谢谢刚刚编辑-重新排序日期。如果解决方案是好的,请接受它作为一个答案。
       dates location    T  SUM2D
0 2020-07-16    Paris  100  300.0
1 2020-07-15    Paris  200  500.0
2 2020-07-14    Paris  300  700.0
3 2020-07-13    Paris  400    NaN
4 2020-07-16       NY   10   30.0
5 2020-07-15       NY   20   50.0
6 2020-07-14       NY   30   70.0
7 2020-07-13       NY   40    NaN