我正在制作一个Pandas df,看起来像这样:
Start End
0 16360 16362
1 16367 16381
2 16374 16399
3 16401 16413
4 16417 16427
5 16428 16437
6 16435 16441
7 16442 16444
8 16457 16463
在此数据帧中,某一行的所有'Start'
个值都在前一行的'End'
个值之后(即row 1: 16367
>;row 0: 16362
),but这对于第2
行和第6
行来说是not true.
我想制作一个计数器i=0
,每次出现这个"错误"时,计数器的长度都会增加(在这种情况下,i
变为i=2
).类似于:
for each Start value of my df:
if the value is < than the End of the row before:
i = i+1
我怎么能对Pandas 这样做?
此外,我想让事情变得更难:我想添加一个'Length'
列,如下所示:
mydf['Length'] = mydf['End'] - mydf['Start']
要获得这样的结果:
Start End Length
0 16360 16362 2
1 16367 16381 4
2 16374 16399 25
3 16401 16413 12
4 16417 16427 10
5 16428 16437 9
6 16435 16441 6
7 16442 16444 2
8 16457 16463 6
同样,对于第2
行和第6
行,我有前面描述的问题.当这个问题出现时,我希望 'Length'
列不再由 'End'
- 'Start'
给出,而是 'End' (i.e., of row 6)
- 'End' (of row 5)
的结果.
在伪代码中可以如下所示:
for each Start value of my df:
if the value is < than the End of the row before:
mydf['Length'] = mydf['End'] of the actual row - mydf['End'] of the row before
非常感谢.