Python将计算输出达到0之前的时间

2024-09-27 04:29:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python中的pandas数据帧,有几个列和一个日期时间戳。其中一列有true/false变量。我想计算时间,直到那个列为假。你知道吗

理想的情况是这样:

datetime             delivered    secondsuntilfailure
2014-05-01 01:00:00    True       3
2014-05-01 01:00:01    True       2
2014-05-01 01:00:02    True       1
2014-05-01 01:00:03    False      0
2014-05-01 01:00:04    True       ?

提前谢谢!!你知道吗


Tags: 数据falsetruepandasdatetime时间情况理想
2条回答

您可以首先通过[::-1]更改顺序,然后查找^{}并计算^{}(如果值是True):

df = df[::-1]
print (df.datetime.diff().astype('timedelta64[s]'))
4    NaN
3   -1.0
2   -1.0
1   -1.0
0   -1.0
Name: datetime, dtype: float64

df['new'] = df.delivered.where(~df.delivered,df.datetime.diff().astype('timedelta64[s]'))
              .cumsum().fillna(0).astype(int).mul(-1)
df = df[::-1]
print (df)
             datetime delivered secondsuntilfailure  new
0 2014-05-01 01:00:00      True                   3    3
1 2014-05-01 01:00:01      True                   2    2
2 2014-05-01 01:00:02      True                   1    1
3 2014-05-01 01:00:03     False                   0    0
4 2014-05-01 01:00:04      True                   ?    0

计算秒数:

cumsecs = df.datetime.diff().astype('timedelta64[s]').cumsum().fillna(value=0.0)

每次交付失败时复制累积值,并填充任何之前的值:

undeliv_secs = cumsecs.where(~df['delivered']).fillna(method='bfill')

直到失败的秒数只是两者之间的区别:

df['secondsuntilfailure'] = undeliv_secs - cumsecs
print(df)
             datetime delivered  secondsuntilfailure
0 2014-05-01 01:00:00      True                  3.0
1 2014-05-01 01:00:01      True                  2.0
2 2014-05-01 01:00:02      True                  1.0
3 2014-05-01 01:00:03     False                  0.0
4 2014-05-01 01:00:04      True                  NaN

相关问题 更多 >

    热门问题