如何对数据帧中的时间求和 [英] How to sum time in a dataframe

查看:64
本文介绍了如何对数据帧中的时间求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个时间数据格式的数据框

I have a dataframe of time data in the format

hh:mm:ss
hh:mm:ss

(类型字符串)

我需要能够对几列中的值求和(以获取总时间).我想知道是否有人对最好的方法提出任何建议,并以相同的格式获取总和.

I need to be able to sum the values (to acquire total time) in a few of the columns. I'm wondering if anyone has any recommendations on the best way to do this and get the sum in the same format.

推荐答案

您可以使用timedelta执行此操作:

You can do this using timedelta:

import pandas as pd
import datetime

data = {'t1':['01:15:31', 
              '00:47:15'], 
        't2':['01:13:02', 
              '00:51:33']
        }

def make_delta(entry):
    h, m, s = entry.split(':')
    return datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s))

df = pd.DataFrame(data)
df = df.applymap(lambda entry: make_delta(entry))

df['elapsed'] = df['t1'] + df['t2']

In [23]: df
Out[23]:
        t1       t2  elapsed
0 01:15:31 01:13:02 02:28:33
1 00:47:15 00:51:33 01:38:48

我看到您需要按列而不是按行执行此操作.在那种情况下,请执行相同的操作,但是:

I see you need to do this by column, not row. In that case do the same thing, but:

In [24]: df['t1'].sum()
Out[24]: Timedelta('0 days 02:02:46')

这篇关于如何对数据帧中的时间求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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