满足条件时如何查找第一行与第一行之间的时差?

时间:2019-05-02 21:10:47

标签: python pandas

我需要找到col1超过值20的开始与瞬间之间的时间差(以分钟为单位)。

对于以下数据,答案应该是72分钟(从20:00:19到21:12:00)。

df

date_time            col1
2018-03-04 20:00:19  9
2018-03-04 21:10:00  13
2018-03-04 21:12:00  21
2018-03-04 21:15:00  25

我该怎么办? 这是我当前的代码段:

df.index = pd.to_datetime(df['date_time'])
start = df.index[0]
row_id = df.index[df['col1'] > 20]
time_val = start - df.index[row_id]

5 个答案:

答案 0 :(得分:4)

一个班轮:

ans = pd.to_datetime(df.groupby(df.col1>20).first().date_time).diff().dt.total_seconds()/60

输出:

ans[True]:

71.68333333333334

答案 1 :(得分:3)

假设'date_time'是dtype datetime。我们可以使用diff来获取Timedelta,使用cumsum来获取累积Timedelta。然后我们可以在idxmax

上使用df.col1.gt(20)
df.date_time.diff().fillna(0).cumsum()[df.col1.gt(20).idxmax()]

Timedelta('0 days 01:11:41')

Timedelta有一个total_seconds方法,您可以将其除以60

df.date_time.diff().fillna(0).cumsum()[df.col1.gt(20).idxmax()].total_seconds() / 60

71.68333333333334

或者您可以除以另一个Timedelta

df.date_time.diff().fillna(0).cumsum()[df.col1.gt(20).idxmax()] / pd.Timedelta(1, unit='m')

71.68333333333334

答案 2 :(得分:2)

IIUC我正在使用ptp

df.loc[df.col1.le(20).shift().cumprod().ne(0),'date_time'].ptp()
Out[1232]: Timedelta('0 days 01:11:41')

答案 3 :(得分:1)

将列转换为所需的输出后:

df.date_time=pd.to_datetime(df.date_time)
df.col1=pd.to_numeric(df.col1)
id=df[df.col1>20].col1.idxmin()
diff=(df.iloc[id].date_time-df.iloc[0].date_time).seconds/60

答案 4 :(得分:0)

您可以尝试以下方法:

for index, row in df1.iterrows():
    if row['col'] > 20:
        total_seconds = int((df1['date_time'][0] - row['date_time']).total_seconds())
        minutes, remainder = divmod(total_seconds,60)
        print('{} mins'.format(minutes))
        break