我正在制作一个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

非常感谢.

推荐答案

您可以使用:

# is the previous End > to the current Start?
m = df['End'].shift().gt(df['Start'])
# propagate error count
df['Error'] = m.cumsum()
# Length = End - Start if no error, else End - previous End
df['Length'] = df['End'].sub(df['Start'].mask(m, df['End'].shift()))

输出:

   Start    End  Error  Length
0  16360  16362      0     2.0
1  16367  16381      0    14.0
2  16374  16399      1    18.0
3  16401  16413      1    12.0
4  16417  16427      1    10.0
5  16428  16437      1     9.0
6  16435  16441      2     4.0
7  16442  16444      2     2.0
8  16457  16463      2     6.0

Python相关问答推荐

为什么调用函数的值和次数不同,递归在代码中是如何工作的?

OpenGL仅渲染第二个三角形,第一个三角形不可见

Cython无法识别Numpy类型

如何使用正则表达式修改toml文件中指定字段中的参数值

将链中的矩阵乘法应用于多组值

Python—在嵌套列表中添加相同索引的元素,然后计算平均值

比较两个有条件的数据帧并删除所有不合格的数据帧

如何将列表从a迭代到z-以抓取数据并将其转换为DataFrame?

Python:使用asyncio.StreamReader.readline()读取长行

Fake pathlib.使用pyfakefs的类变量中的路径'

如何从具有完整层次数据的Pandas框架生成图形?

为什么任何一个HTML页面在保存到文件后都会变大6个字节?

颂歌中的线性插值法(盖柯)

.yml不会在专用环境中安装来自.requirements.txt的软件包

.pth文件如何区分带有路径信息的行和带有Python代码的行?

Selify urllib.error.HTTPError:HTTP错误404:未找到

允许在枚举中使用一组特定的未定义值

从数据帧中 Select 变量S类别

在所有任务完成之前完成Python事件循环

确定pymongo文档的数量