python中的每周数据有什么方法可以计算吗?

Is there any way to calculate the weekly data in python?

我对数据框有疑问。我想在一周开始减去一周结束时得到结果。有什么办法吗?

Week Number Position Desired Results Operation
1 2
1 2
1 2 0 2-2
2 4
2 6
3 7 3 7-4
3 12
3 14
3 15 3 15-12

尝试 groupbytransform:

df['Desired'] = df.groupby('Week Number')['Position'].transform(lambda x: x.iloc[-1] - x.iloc[0])

现在:

>>> df
   Week Number  Position  Desired
0            1         2        0
1            1         2        0
2            1         2        0
3            2         4        3
4            2         6        3
5            2         7        3
6            3        12        3
7            3        14        3
8            3        15        3
>>> 

或者先赋值给变量:

group = df.groupby('Week Number')['Position']
df['Desired'] = group.transform('last') - group.transform('first')

编辑:

要避免重复,请尝试:

df['Desired'] = df.groupby('Week Number')['Position'].transform(lambda x: [''] * (len(x) - 1) + [x.iloc[-1] - x.iloc[0]])

现在:

>>> df
   Week Number  Position Desired
0            1         2        
1            1         2        
2            1         2       0
3            2         4        
4            2         6        
5            2         7       3
6            3        12        
7            3        14        
8            3        15       3
>>>