>我有一个时间数据的数据帧,格式为
hh:mm:ss
hh:mm:ss
(类型字符串)
我需要能够对几列中的值求和(以获取总时间)。 我想知道是否有人对执行此操作并以相同格式获取总和的最佳方法有任何建议。
您可以使用 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
编辑:我看到您需要按列而不是行执行此操作。 在这种情况下,请执行相同的操作,但是:
In [24]: df['t1'].sum()
Out[24]: Timedelta('0 days 02:02:46')
您可以将
to_timedelta
与sum
一起使用:
import pandas as pd
df = pd.DataFrame({'A': ['18:22:28', '12:15:10']})
df['A'] = pd.to_timedelta(df.A)
print (df)
A
0 18:22:28
1 12:15:10
print (df.dtypes)
A timedelta64[ns]
dtype: object
print (df.A.sum())
1 days 06:37:38
也许尝试使用datetime.timedelta
?
import re
from datetime import timedelta
_TIME_RE = re.compile(r'(d+):(d+):(d+)')
def parse_timedelta(line):
# Invalid lines (such as blank) will be considered 0 seconds
m = _TIME_RE.match(line)
if m is None:
return timedelta()
hours, minutes, seconds = [int(i) for i in m.groups()]
return timedelta(hours=hours, minutes=minutes, seconds=seconds)
def format_timedelta(delta):
hours, rem = divmod(delta.seconds + delta.days * 86400, 3600)
minutes, seconds = divmod(rem, 60)
return '{:02}:{:02}:{:02}'.format(hours, minutes, seconds)
如果data
是包含以下行的列表:
print(format_timedelta(sum(parse_timedelta(line) for line in data)))