繁体   English   中英

在 pandas 数据帧的行中添加时间,在数据帧的新列中添加 append total_time

[英]add time in rows of pandas data frame and append total_time in new column of data frame

我正在创建一个 dataframe 如下所示

df1 = df =pd.DataFrame({'Month_Year':['January_208','January_208','January_208','Febuary_208','Febuary_208'],
                  'Date':['11','11','12','15','15'],
                  'Video_Name':['17-29_202100000.avi','17-29_2055500000.avi','17-29_202150000.avi','17-29_202145000.avi','17-29_202100000.avi'],
                  'Video_Length':['55:11:12','222:10:05','22:02:01','11:00:03','34:20:32'],
                  
})

所以 dataframe 就像在此处输入图像描述 现在想在月年和日期相同的地方添加video_length列的时间,并希望 append 数据帧的新列中的这些值,即total_time例如第一行和第二行我们有相同的月份和日期,我们想在新的时间和 append第 4 行和第 5 行的列 total_time 类似。预期 output 在此处输入图像描述

使用to_timedelta将值转换为 timedeltas,然后将GroupBy.transformsum用于由聚合值填充的新列,并通过最终timedelta s 的自定义 function 的最后更改格式:

df1['Video_Length'] = pd.to_timedelta(df1['Video_Length'])

def format_timedelta(x):
    ts = x.total_seconds()
    hours, remainder = divmod(ts, 3600)
    minutes, seconds = divmod(remainder, 60)
    return ('{}:{:02d}:{:02d}').format(int(hours), int(minutes), int(seconds)) 
    

df1['Total_time'] = (df1.groupby(['Month_Year','Date'])['Video_Length'].transform('sum')
                        .apply(format_timedelta))
print (df1)
    Month_Year Date            Video_Name    Video_Length Total_time
0  January_208   11   17-29_202100000.avi 2 days 07:11:12  277:21:17
1  January_208   11  17-29_2055500000.avi 9 days 06:10:05  277:21:17
2  January_208   12   17-29_202150000.avi 0 days 22:02:01   22:02:01
3  Febuary_208   15   17-29_202145000.avi 0 days 11:00:03   45:20:35
4  Febuary_208   15   17-29_202100000.avi 1 days 10:20:32   45:20:35

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM