Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

python - How to sum time in a dataframe

I have a dataframe of time data in the format

hh:mm:ss
hh:mm:ss

(type string)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

Edit: 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')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...