使用datetime pandas 按照持续时间创建行 [英] Creating rows as per duration using datetime pandas

查看:63
本文介绍了使用datetime pandas 按照持续时间创建行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一个使用datetime编写代码的问题.我创建了一个正在研究的方案.有人可以帮我解决代码上的问题.

I am facing an issue to write a code using datetime. I had created a scenario I am working on. Can someone help me out on the code.

输入:

Name, Channel, Duration, Start_time
John, A, 2, 16:00:00
Joseph, B, 3, 15:05:00

输出:

Name, Channel, Duration, Start_time
John, A, 2, 16:00:00
John, A, 2, 16:01:00
Joseph, B, 3, 15:05:00
Joseph, B, 3, 15:06:00
Joseph, B, 3, 15:07:00

谢谢.

推荐答案

使用:

df['Start_time'] = pd.to_timedelta(df['Start_time'])
df = df.loc[df.index.repeat(df['Duration'])]
td = pd.to_timedelta(df.groupby(level=0).cumcount() * 60, unit='s')

df['Start_time'] = df['Start_time'] + td
df = df.reset_index(drop=True)

print (df)
     Name Channel  Duration Start_time
0    John       A         2   16:00:00
1    John       A         2   16:01:00
2  Joseph       B         3   15:05:00
3  Joseph       B         3   15:06:00
4  Joseph       B         3   15:07:00

说明:

  1. 对转换列进行开始时间 to_timedelta
  2. 然后 重复按列 Duration 的索引值,并按 创建计数器>每个索引值的累积量 ,并将其转换为1分钟的时间增量,并将其添加到新的重复列 Start_time
  3. 最后 重置索引使用参数 drop = True 以避免重复的索引值
  1. Firt convert column Start_time to_timedelta
  2. Then repeat values of index by column Duration and repeat rows by loc
  3. Create counter by cumcount per index values and convert it to 1 minute timedeltas, which are added to new repeated column Start_time
  4. Last reset_index with parameter drop=True for avoid duplicated index values

如果希望输出解决方案中的日期时间相同,则仅首先转换值

If want datetimes in output solution is same, only first convert values to_datetime:

df['Start_time'] = pd.to_datetime(df['Start_time'])
df = df.loc[df.index.repeat(df['Duration'])]
td = pd.to_timedelta(df.groupby(level=0).cumcount() * 60, unit='s')

df['Start_time'] = df['Start_time'] + td
df = df.reset_index(drop=True)
print (df)
     Name Channel  Duration          Start_time
0    John       A         2 2018-11-19 16:00:00
1    John       A         2 2018-11-19 16:01:00
2  Joseph       B         3 2018-11-19 15:05:00
3  Joseph       B         3 2018-11-19 15:06:00
4  Joseph       B         3 2018-11-19 15:07:00

这篇关于使用datetime pandas 按照持续时间创建行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆