这是我的pandas DataFrame:
import pandas as pd
import numpy as np
data = {"column1": [338,519,871,1731,2693,2963,3379,3789,3910,4109,4307,4800,4912,5111,5341,5820,6003,...],"column2": [NaN,1,NaN,2,3,NaN],...}
df = pd.DataFrame(data)
df
>>> column1 column2
0 338 NaN
1 519 1.0
2 871 1.0
3 1731 1.0
4 2693 1.0
5 2963 NaN
6 3379 NaN
7 3789 2.0
8 3910 2.0
9 4109 NaN
10 4307 NaN
11 4800 3.0
12 4912 3.0
13 5111 3.0
14 5341 3.0
15 5820 3.0
16 6003 NaN
17 .... ....
column2中的整数表示column1中的“groups”,例如:行1-4是组“1”,行7-8是组“2”,行11-15是组“3”等.
我想计算每组中第一行和最后一行之间的差异.结果数据框如下所示:
df
>>> column1 column2 column3
0 338 NaN NaN
1 519 1.0 2174
2 871 1.