Python如何合并时间跨度并制作更大的时间跨度

如何解决Python如何合并时间跨度并制作更大的时间跨度

我有以下数据框。

       padel start_time  end_time  duration
38  Padel 10   08:00:00  09:00:00        60
40  Padel 10   10:00:00  11:30:00        90
42  Padel 10   10:30:00  12:00:00        90
44  Padel 10   11:00:00  12:30:00        90
46  Padel 10   11:30:00  13:00:00        90
49  Padel 10   16:00:00  17:30:00        90
51  Padel 10   16:30:00  18:00:00        90
53  Padel 10   17:00:00  18:30:00        90
55  Padel 10   17:30:00  19:00:00        90
57  Padel 10   18:00:00  19:30:00        90
59  Padel 10   18:30:00  20:00:00        90
61  Padel 10   19:00:00  20:30:00        90
63  Padel 10   19:30:00  21:00:00        90
65  Padel 10   20:00:00  21:30:00        90
67  Padel 10   20:30:00  22:00:00        90

我想选择两者之间最长的时间跨度。我想要的输出应该是这样的

       padel start_time  end_time  duration
38  Padel 10   08:00:00  09:00:00        60
40  Padel 10   10:00:00  13:00:00        180
49  Padel 10   16:00:00  22:00:00        360

我不在乎持续时间。我可以做到。但是我将如何合并重叠的时间跨度。 谢谢

解决方法

  1. 如果 shift() 是上面行的 start_time greater than(即重叠),您可以使用 end_time 创建组。
  2. 我们将 fillna'24:00:00' 一起使用,以便我们为第一个值返回“True”,因为一天中没有任何东西可以超过 24 小时。这是因为 NaN 是带有 shift() 的第一行的输出,如果我们不这样做,它将返回 False
  3. 这将返回一个 boolean 系列的 TrueFalse(即分别为 10),因此您只需将累积总和与cumsum
  4. 这会创建一个 grp 对象,我们可以将其包含在 groupby 中。

df = df.sort_values(by=['padel','start_time'],ascending=[True,True])
grp = df['start_time'].gt(df['end_time'].shift().fillna('24:00:00')).cumsum() 
df = df.groupby([grp,'padel'],as_index=False).agg({'start_time':'first','end_time':'last'})
df['duration'] = ((pd.to_timedelta(df['end_time']) - 
                   pd.to_timedelta(df['start_time'])).dt.seconds / 60).astype(int)
Out[1]: 
      padel start_time  end_time  duration
0  Padel 10   08:00:00  09:00:00        60
1  Padel 10   10:00:00  13:00:00       180
2  Padel 10   16:00:00  22:00:00       360

带有输入数据框的完整代码

df = pd.DataFrame(pd.DataFrame({'padel': {38: 'Padel 10',40: 'Padel 10',42: 'Padel 10',44: 'Padel 10',46: 'Padel 10',49: 'Padel 10',51: 'Padel 10',53: 'Padel 10',55: 'Padel 10',57: 'Padel 10',59: 'Padel 10',61: 'Padel 10',63: 'Padel 10',65: 'Padel 10',67: 'Padel 10'},'start_time': {38: '08:00:00',40: '10:00:00',42: '10:30:00',44: '11:00:00',46: '11:30:00',49: '16:00:00',51: '16:30:00',53: '17:00:00',55: '17:30:00',57: '18:00:00',59: '18:30:00',61: '19:00:00',63: '19:30:00',65: '20:00:00',67: '20:30:00'},'end_time': {38: '09:00:00',40: '11:30:00',42: '12:00:00',44: '12:30:00',46: '13:00:00',49: '17:30:00',51: '18:00:00',53: '18:30:00',55: '19:00:00',57: '19:30:00',59: '20:00:00',61: '20:30:00',63: '21:00:00',65: '21:30:00',67: '22:00:00'},'duration': {38: 60,40: 90,42: 90,44: 90,46: 90,49: 90,51: 90,53: 90,55: 90,57: 90,59: 90,61: 90,63: 90,65: 90,67: 90}}))
grp = df['start_time'].gt(df['end_time'].shift().fillna('24:00:00')).cumsum() 
df = df.groupby([grp,'end_time':'last'})
df['duration'] = ((pd.to_timedelta(df['end_time']) - \
                   pd.to_timedelta(df['start_time'])).dt.seconds / 60).astype(int)
df
,
#Coeece the start and end times to datetime
df['start_time']=pd.to_datetime(df['start_time'])
df['end_time']=pd.to_datetime(df['end_time'])

g=df.groupby(df.end_time.sub(df.start_time.shift(1)).ne('2h').cumsum()).tail(1).reset_index()#Find last entry in each set of pedal

g=g.assign(start_time=df.groupby(df.end_time.sub(df.start_time.shift(1)).ne('2h').cumsum()).start_time.head(1).reset_index().loc[:,'start_time'])#Set start_time to the start_time in each set of pedal


g=g.iloc[:,:-1].join(df.groupby(df.end_time.sub(df.start_time.shift(1)).ne('2h').cumsum()).apply(lambda x: (x['end_time'].max()-(x['start_time'].min())).total_seconds()/60).to_frame('duration').reset_index(drop=True))#Calc the duration



    padel start_time  end_time  duration
0  Padel 10   08:00:00  09:00:00        60
1  Padel 10   10:00:00  13:00:00       180
2  Padel 10   16:00:00  22:00:00       360
,

我想不出一个简单的熊猫方法来做到这一点,所以我只需要一个 for 循环。尚未测试此代码,但类似于:

df = df.sort_values(...)
out_df = pd.DataFrame(columns=df.columns)
next_row = None

for row in df.rows:
    if next_row is None:
        next_row = row
    elif row['start_time'] <= next_row['end_time']:
        next_row['end_time'] = row['end_time']
    else:
        out_df = out_df.append(next_row)
        next_row = None

out_df = out_df.append(next_row)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-