Python 编写应用于熊猫数据框的函数,该数据框查看问题上的行和上面的行

Python 编写应用于熊猫数据框的函数,该数据框查看问题上的行和上面的行,python,pandas,Python,Pandas,我有一个熊猫数据框,如下所示: Start End 2017-12-21 2017-12-23 2018-01-01 2018-01-05 2018-01-04 2018-01-07 2018-03-05 2018-09-06 我想写一个函数,检查Start中的值是否在上行的Start和End之间,并相应地将overlawWithOverrow设置为1或0 Start End OverlapWithAboveRow 2017-12-21 201

我有一个熊猫数据框,如下所示:

Start       End
2017-12-21  2017-12-23
2018-01-01  2018-01-05
2018-01-04  2018-01-07
2018-03-05  2018-09-06
我想写一个函数,检查Start中的值是否在上行的Start和End之间,并相应地将overlawWithOverrow设置为1或0

Start       End         OverlapWithAboveRow
2017-12-21  2017-12-23  0
2018-01-01  2018-01-05  0
2018-01-04  2018-01-07  1
2018-03-05  2018-09-06  0
我该怎么做?是否可以编写一个函数用于引用行及其上一行的值的apply方法

我知道可以使用for循环,但它相当慢,我认为可能有一种更快的方法

for i in df.index:
    if df.loc[i-1,'Start'] <= df.loc[i,'Start'] <= df.loc[i-1,'End']:
        df.loc[i,'OverlapWithAboveRow'] = 1
df.index中的i的

如果df.loc[i-1,'Start']不需要使用循环,您可以使用
shift
返回布尔序列并将类型指定为
int
,然后将其设置为新列名

df['OverlapWithAboveRow'] = df['Start'].between(df['Start'].shift(), df['End'].shift()).astype(int)

       Start        End     OverlapWithAboveRow
0   2017-12-21  2017-12-23       0
1   2018-01-01  2018-01-05       0
2   2018-01-04  2018-01-07       1
3   2018-03-05  2018-09-06       0
如果确实要创建函数,可以:

def myFunc(df, start, end):
    """
    df is the dataframe
    start is the name of the column for the start times
    end is the name of the column for the end times
    """
    return df[start].between(df[start].shift(), df[end].shift()).astype(int)

df['OverlapWithAboveRow'] = myFunc(df, 'Start', 'End')