列中的行之间的时间间隔,python

发布于 2025-02-08 20:59:24 字数 723 浏览 2 评论 0原文

输入

New Time
11:59:57
12:42:10
12:48:45
18:44:53 
18:49:06
21:49:54
21:54:48
 5:28:20 

下面我编写了代码以在最小值中创建间隔。

import pandas as pd
import numpy as np

df = pd.read_csv(r"D:\test\test1.csv")

df['Interval in min'] = (pd.to_timedelta(df['New Time'].astype(str)).diff(1).dt.floor('T').dt.total_seconds().div(60))
print(df)

输出

New Time  Interval in min
11:59:57              NaN
12:42:10             42.0
12:48:45              6.0
18:44:53            356.0
18:49:06              4.0
21:49:54            180.0
21:54:48              4.0
 5:28:20           -987.0

最后一个间隔IE -987分钟不正确,宁愿是453分钟(+1天)。

Input

New Time
11:59:57
12:42:10
12:48:45
18:44:53 
18:49:06
21:49:54
21:54:48
 5:28:20 

Below I wrote code to create interval in min.

import pandas as pd
import numpy as np

df = pd.read_csv(r"D:\test\test1.csv")

df['Interval in min'] = (pd.to_timedelta(df['New Time'].astype(str)).diff(1).dt.floor('T').dt.total_seconds().div(60))
print(df)

Output

New Time  Interval in min
11:59:57              NaN
12:42:10             42.0
12:48:45              6.0
18:44:53            356.0
18:49:06              4.0
21:49:54            180.0
21:54:48              4.0
 5:28:20           -987.0

Last interval in min i.e. -987 min is not correct, it should rather be 453 min (+1 day).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

驱逐舰岛风号 2025-02-15 20:59:24

假设您想将负差异视为新的一天,则可以使用:

s = pd.to_timedelta(df['New Time']).diff()
df['Interval in min'] = (s
  .add(pd.to_timedelta(s.lt('0').cumsum(), unit='d'))
  .dt.floor('T').dt.total_seconds().div(60)
)

输出:

   New Time  Interval in min
0  11:59:57              NaN
1  12:42:10             42.0
2  12:48:45              6.0
3  18:44:53            356.0
4  18:49:06              4.0
5  21:49:54            180.0
6  21:54:48              4.0
7   5:28:20            453.0

Assuming you want to consider a negative difference to be a new day, you could use:

s = pd.to_timedelta(df['New Time']).diff()
df['Interval in min'] = (s
  .add(pd.to_timedelta(s.lt('0').cumsum(), unit='d'))
  .dt.floor('T').dt.total_seconds().div(60)
)

output:

   New Time  Interval in min
0  11:59:57              NaN
1  12:42:10             42.0
2  12:48:45              6.0
3  18:44:53            356.0
4  18:49:06              4.0
5  21:49:54            180.0
6  21:54:48              4.0
7   5:28:20            453.0
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文