无法操作日期时间.timedelta具有块值的(0,3600)必须是str,而不是日期时间.timed

2024-04-27 00:39:13 发布

您现在位置:Python中文网/ 问答频道 /正文

这里有一个数据集,包含日期、时间和一个输入。在这里,我想为特定时间添加timedelta,并添加到datetime列。你知道吗

因此,首先我将指定时间转换为00:00:00,它将是开始时间。从那时起我想加上一个小时,一个小时到6的范围。然后我想把它添加到datetime列中。你知道吗

我写了代码,但它给了我错误:Could not operate datetime.timedelta(0, 3600) with block values must be str, not datetime.timedelta

我的代码是:

data['date_time']= pd.to_datetime(data['date'] + " " + data['time'],
                        format='%d/%m/%Y %H:%M:%S', dayfirst=True)
mask = data['X3'].eq(5)
data['duration'] = data['date_time'].mask(mask, data['date_time'].dt.floor('d'))

T= pd.DataFrame({"data['duration']":[ "00:00:00" for i in range(3) ]},index=np.random.randint(0,100,3))
for it in range(1,4):
 Time = T +timedelta(hours=1*it)

出现错误:

TypeError Traceback (most recent call last) ~\Anaconda3\lib\site-packages\pandas\core\ops.py in na_op(x, y) 1466 try: -> 1467 result = expressions.evaluate(op, str_rep, x, y, **eval_kwargs) 1468 except TypeError: ~\Anaconda3\lib\site-packages\pandas\core\computation\expressions.py in evaluate(op, op_str, a, b, use_numexpr, **eval_kwargs) 204 if use_numexpr: --> 205 return _evaluate(op, op_str, a, b, **eval_kwargs) 206 return _evaluate_standard(op, op_str, a, b) ~\Anaconda3\lib\site-packages\pandas\core\computation\expressions.py in _evaluate_numexpr(op, op_str, a, b, truediv, reversed, **eval_kwargs) 119 if result is None: --> 120 result = _evaluate_standard(op, op_str, a, b) 121 ~\Anaconda3\lib\site-packages\pandas\core\computation\expressions.py in _evaluate_standard(op, op_str, a, b, **eval_kwargs) 64 with np.errstate(all='ignore'): ---> 65 return op(a, b) 66 TypeError: must be str, not datetime.timedelta During handling of the above exception, another exception occurred: TypeError Traceback (most recent call last) ~\Anaconda3\lib\site-packages\pandas\core\internals.py in eval(self, func, other, errors, try_cast, mgr) 1414 with np.errstate(all='ignore'): -> 1415 result = get_result(other) 1416 ~\Anaconda3\lib\site-packages\pandas\core\internals.py in get_result(other) 1382 else: -> 1383 result = func(values, other) 1384 ~\Anaconda3\lib\site-packages\pandas\core\ops.py in na_op(x, y) 1494 with np.errstate(all='ignore'): -> 1495 result[mask] = op(xrav, y) 1496 else: TypeError: must be str, not datetime.timedelta During handling of the above exception, another exception occurred: TypeError Traceback (most recent call last) <ipython-input-95-771f9e94063d> in <module>() 13 T= pd.DataFrame({"data['duration']":[ "00:00:00" for i in range(3) ]},index=np.random.randint(0,100,3)) 14 for it in range(1,7): ---> 15 Time = T +timedelta(hours=1*it) ~\Anaconda3\lib\site-packages\pandas\core\ops.py in f(self, other, axis, level, fill_value) 1527 self = self.fillna(fill_value) 1528 -> 1529 return self._combine_const(other, na_op, try_cast=True) 1530 1531 f.__name__ = op_name ~\Anaconda3\lib\site-packages\pandas\core\frame.py in _combine_const(self, other, func, errors, try_cast) 4774 new_data = self._data.eval(func=func, other=other, 4775 errors=errors, -> 4776 try_cast=try_cast) 4777 return self._constructor(new_data) 4778 ~\Anaconda3\lib\site-packages\pandas\core\internals.py in eval(self, **kwargs) 3685 3686 def eval(self, **kwargs): -> 3687 return self.apply('eval', **kwargs) 3688 3689 def quantile(self, **kwargs): ~\Anaconda3\lib\site-packages\pandas\core\internals.py in apply(self, f, axes, filter, do_integrity_check, consolidate, **kwargs) 3579 3580 kwargs['mgr'] = self -> 3581 applied = getattr(b, f)(**kwargs) 3582 result_blocks = _extend_blocks(applied, result_blocks) 3583 ~\Anaconda3\lib\site-packages\pandas\core\internals.py in eval(self, func, other, errors, try_cast, mgr) 1420 raise 1421 except Exception as detail: -> 1422 result = handle_error() 1423 1424 # technically a broadcast error in numpy can 'work' by returning a ~\Anaconda3\lib\site-packages\pandas\core\internals.py in handle_error() 1403 raise TypeError( 1404 'Could not operate {other!r} with block values ' -> 1405 '{detail!s}'.format(other=other, detail=detail)) # noqa 1406 else: 1407 # return the values TypeError: Could not operate datetime.timedelta(0, 3600) with block values must be str, not datetime.timedelta

我期望的结果是:

date time x3 expected output x3 (add) timedelta 10/3/2018 6:15:00 7 10/3/2018 6:15:00 10/3/2018 6:45:00 5 10/3/2018 6:45:00 5 0:00:00 10/3/2018 7:45:00 7 10/3/2018 7:45:00 1:00:00 10/3/2018 9:00:00 7 10/3/2018 8:45:00 2:00:00 10/3/2018 9:25:00 7 10/3/2018 9:30:00 second 5 0:00:00 10/3/2018 9:30:00 5 10/3/2018 9:45:00 3:00:00 10/3/2018 11:00:00 7 10/3/2018 10:30:00 1:00:00 10/3/2018 11:30:00 7 10/3/2018 10:45:00 2:00:00 10/3/2018 13:30:00 7 10/3/2018 10:45:00 4:00:00 10/3/2018 13:50:00 5 10/3/2018 11:30:00 3:00:00 10/3/2018 15:00:00 7 10/3/2018 12:30:00 4:00:00 10/3/2018 15:25:00 7 10/3/2018 16:25:00 7 10/3/2018 18:00:00 5 10/3/2018 19:00:00 7 10/3/2018 19:30:00 7

我的csv文件: My csv file

所以这里我想增加我的数据长度,加上这个时间增量。 有人能帮我解决这个错误吗?你知道吗

For the reference expected output x3 (add) timedelta 10/3/2018 6:15:00 10/3/2018 6:45:00 5 0:00:00 10/3/2018 7:45:00 1:00:00 10/3/2018 8:45:00 2:00:00 10/3/2018 9:30:00 second 5 0:00:00 10/3/2018 9:45:00 3:00:00 10/3/2018 10:30:00 1:00:00 10/3/2018 10:45:00 2:00:00 10/3/2018 10:45:00 4:00:00 10/3/2018 11:30:00 3:00:00 10/3/2018 12:30:00 4:00:00 Here you can till to 10:45:00 I need to give time range (4) after starting the new time also

Tags: inpycoreselfpandasdatalibpackages
1条回答
网友
1楼 · 发布于 2024-04-27 00:39:13

我尝试创建没有循环的解决方案:

#datetime column
data['date_time']= pd.to_datetime(data['date'] + " " + data['time'],
                        format='%d/%m/%Y %H:%M:%S', dayfirst=True)
#set starts 00:00:00
mask = data['x3'].eq(5)
data['duration'] = data['date_time'].mask(mask, data['date_time'].dt.floor('d'))

#create helper group column
m = mask.cumsum()
#create counter per groups, but first group (values before first 5) are set to 0
data['g'] = data[m != 0].groupby(m).cumcount()
#all values > 5 aare set to 0, not > 6 because python counts from 0
data['g'] = data['g'].fillna(0).mask(data['g'] > 5, 0)
#get values of date_time only for 5 and forward filling it
first = data.loc[mask, 'date_time'].reindex(data.index, method='ffill')
#converting hours to timedeltas and add to duration column
data['duration'] = pd.to_timedelta(data['g'], unit='h') + first

print (data)
         date      time  x3           date_time            duration    g
0   10/3/2018   6:15:00   7 2018-03-10 06:15:00                 NaT  0.0
1   10/3/2018   6:45:00   5 2018-03-10 06:45:00 2018-03-10 06:45:00  0.0
2   10/3/2018   7:45:00   7 2018-03-10 07:45:00 2018-03-10 07:45:00  1.0
3   10/3/2018   9:00:00   7 2018-03-10 09:00:00 2018-03-10 08:45:00  2.0
4   10/3/2018   9:25:00   7 2018-03-10 09:25:00 2018-03-10 09:45:00  3.0
5   10/3/2018   9:30:00   5 2018-03-10 09:30:00 2018-03-10 09:30:00  0.0
6   10/3/2018  11:00:00   7 2018-03-10 11:00:00 2018-03-10 10:30:00  1.0
7   10/3/2018  11:30:00   7 2018-03-10 11:30:00 2018-03-10 11:30:00  2.0
8   10/3/2018  13:30:00   7 2018-03-10 13:30:00 2018-03-10 12:30:00  3.0
9   10/3/2018  13:50:00   5 2018-03-10 13:50:00 2018-03-10 13:50:00  0.0
10  10/3/2018  15:00:00   7 2018-03-10 15:00:00 2018-03-10 14:50:00  1.0
11  10/3/2018  15:25:00   7 2018-03-10 15:25:00 2018-03-10 15:50:00  2.0
12  10/3/2018  16:25:00   7 2018-03-10 16:25:00 2018-03-10 16:50:00  3.0
13  10/3/2018  18:00:00   5 2018-03-10 18:00:00 2018-03-10 18:00:00  0.0
14  10/3/2018  19:00:00   7 2018-03-10 19:00:00 2018-03-10 19:00:00  1.0
15  10/3/2018  19:30:00   7 2018-03-10 19:30:00 2018-03-10 20:00:00  2.0
16  10/3/2018  20:00:00   7 2018-03-10 20:00:00 2018-03-10 21:00:00  3.0
17  10/3/2018  22:05:00   7 2018-03-10 22:05:00 2018-03-10 22:00:00  4.0
18  10/3/2018  22:15:00   5 2018-03-10 22:15:00 2018-03-10 22:15:00  0.0
19  10/3/2018  23:40:00   7 2018-03-10 23:40:00 2018-03-10 23:15:00  1.0
20  10/4/2018   6:58:00   5 2018-04-10 06:58:00 2018-04-10 06:58:00  0.0
21  10/4/2018  13:00:00   7 2018-04-10 13:00:00 2018-04-10 07:58:00  1.0
22  10/4/2018  16:00:00   7 2018-04-10 16:00:00 2018-04-10 08:58:00  2.0
23  10/4/2018  17:00:00   7 2018-04-10 17:00:00 2018-04-10 09:58:00  3.0
24  10/4/2018  18:00:00   7 2018-04-10 18:00:00 2018-04-10 10:58:00  4.0
25  10/5/2018   7:00:00   7 2018-05-10 07:00:00 2018-04-10 11:58:00  5.0
26  10/5/2018   8:00:00   7 2018-05-10 08:00:00 2018-04-10 06:58:00  0.0
27  10/5/2018   9:00:00   7 2018-05-10 09:00:00 2018-04-10 06:58:00  0.0

相关问题 更多 >