问题描述
我有这样的数据:
user in out location flag Time
0 ron 12/21/2021 10:11 12/21/2016 17:50 home 0 4:19:03
1 ron 12/21/2016 13:26 12/21/2016 13:52 office 2 0:25:28
2 april 12/21/2016 8:12 12/21/2016 17:27 office 0 8:15:03
3 april 12/21/2016 18:54 12/21/2016 22:56 office 0 4:02:36
4 andy 12/21/2016 8:57 12/21/2016 12:15 home 0 2:59:40
我想根据标志对每个用户的时间求和或取最大值.所以我将列转换为 timedelta.
I want to sum or take the max value of time per user based on the flag. So I converted the column to timedelta.
sample.loc[:,'Time'] = pd.to_timedelta(sample['Time'])
但是,当我尝试通过对整列求和来测试这一点时
However, when I try to test this by summing the entire column
sum(sample['Time'])
我收到以下错误:
TypeError: unsupported operand type(s) for +: 'int' and 'Timedelta'
我在这里错过了什么?我以为你可以用 Timedelta 求和.
What am I missing here? I thought you could sum with Timedelta.
推荐答案
Python 的 sum
,默认情况下假定您正在对整数求和.因此它尝试从 0
开始求和,这就是这个错误的来源.不可能将 0
添加到 timedelta.
Python's sum
, by default, assumes you are summing integers. Hence it tries to start summing from 0
, which is where this error comes from. It's impossible to add 0
to a timedelta.
这可以通过两种方式修复:
This can be fixed in 2 ways:
为
sum
提供一个不同的起始值,可能是一个空的"timedelta
,作为sum
:
Provide a different starting value to
sum
, perhaps an "empty"timedelta
, as the second argument forsum
:
from datetime import timedelta
...
sum(sample['Time'], timedelta())
使用Series.sum
(无论如何它可能会有更好的性能):
Use Series.sum
(which will probably have better performance anyway):
sample['Time'].sum()
这篇关于使用 timedelta 的 TypeError,无法求和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!