使用datetime pandas 按照持续时间创建行 [英] Creating rows as per duration using datetime pandas
本文介绍了使用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
说明:
- 对转换列进行
开始时间
to_timedelta
- 然后
重复
按列Duration
的索引值,并按创建计数器>每个索引值的累积量
,并将其转换为1分钟的时间增量,并将其添加到新的重复列Start_time
中 - 最后
重置索引
使用参数drop = True
以避免重复的索引值
- Firt convert column
Start_time
to_timedelta
- Then
repeat
values of index by columnDuration
and repeat rows byloc
- Create counter by
cumcount
per index values and convert it to 1 minute timedeltas, which are added to new repeated columnStart_time
- Last
reset_index
with parameterdrop=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屋!
查看全文