python - 如何使用python为每次单独包含在一列中添加timedelta
问题描述
在这里,我有一个数据集,其中包含输入以及日期和时间。在这里,我只想将输入列中包含的特定值的时间转换为 00:00:00,其他时间将按原样显示。然后我为此编写了代码。然后我想要的是仅指定 00:00:00 。所以我为它写了代码。
这是我的代码:
data['time_diff']= pd.to_datetime(data['date'] + " " + data['time'],
format='%d/%m/%Y %H:%M:%S', dayfirst=True)
data['duration'] = np.where(data['X3'].eq(5), np.timedelta64(0), pd.to_timedelta(data['time']))
print (data['duration'].dtype)
def f(x):
ts = x.total_seconds()
hours, remainder = divmod(ts, 3600)
minutes, seconds = divmod(remainder, 60)
return ('{:02d}:{:02d}:{:02d}').format(int(hours), int(minutes), int(seconds))
data['duration'] = data['duration'].apply(f)
match_time="00:00:00"
T = data.loc[data['duration'] == match_time, 'duration']
然后我得到了输出:
然后我想做的是我只想为每个时间序列添加 6 小时然后我为它编写了代码,它只给了我 0 个值而没有单独的。
我的代码:
def time (y):
S=[]
row=0
for row in range(len(T)):
y = "00:00:00"
while row >0:
S = np.array(y + np.timedelta(hours=i) for i in range(6))
row += 1
break
else:
continue
#break
return
A= T.apply(time)
print(A)
然后输出来了:
但我期望的是:
T add timedelta 1hr till to 6 hrs expected output
00:00:00 01:00:00
" 02:00:00
03:00:00
04:00:00
" 05:00:00
06:00:00
00:00:00 " 01:00:00
02:00:00
03:00:00
04:00:00
05:00:00
06:00:00
00:00:00:00 01:00:00
02:00:00
03:00:00
04:00:00
05:00:00
06:00:00
解决方案
也许这就是你的想法:
My test data frame:
T= pd.DataFrame({"T":[ "00:00:00" for i in range(3) ]},index=np.random.randint(0,100,3))
T
8 00:00:00
96 00:00:00
44 00:00:00
tims=[ dt.time(i).strftime("%H:%M:%S") for i in range(1,7)]
['01:00:00', '02:00:00', '03:00:00', '04:00:00', '05:00:00', '06:00:00']
dd=T.apply(lambda r: pd.Series({"T":"00:00:00", "Hours":tims}), axis=1)
T Hours
8 00:00:00 [01:00:00, 02:00:00, 03:00:00, 04:00:00, 05:00...
96 00:00:00 [01:00:00, 02:00:00, 03:00:00, 04:00:00, 05:00...
44 00:00:00 [01:00:00, 02:00:00, 03:00:00, 04:00:00, 05:00...
dd.explode("Hours")
T Hours
8 00:00:00 01:00:00
8 00:00:00 02:00:00
8 00:00:00 03:00:00
8 00:00:00 04:00:00
8 00:00:00 05:00:00
8 00:00:00 06:00:00
44 00:00:00 01:00:00
44 00:00:00 02:00:00
44 00:00:00 03:00:00
44 00:00:00 04:00:00
44 00:00:00 05:00:00
44 00:00:00 06:00:00
96 00:00:00 01:00:00
96 00:00:00 02:00:00
96 00:00:00 03:00:00
96 00:00:00 04:00:00
96 00:00:00 05:00:00
96 00:00:00 06:00:00
推荐阅读
- javascript - 在 vue 模板中渲染一个孩子
- javascript - /dist 中的 index.html 在保存时被删除,并且在 webpack 监视模式期间不会再次重新构建(如果没有更改文件)
- node.js - 当我尝试传递 json 对象进行测试时,Mocha 测试获取“在位置 1 的 JSON 中获取 500 个意外的 JSON o”
- python-3.x - AssertionError: `assert not _is_device_list_single_worker(devices)` 在使用 TF 2.1 的镜像策略在 AI 平台上训练估计器时
- gradle - 当我只删除一个单词时,为什么 Body 构建中的代码会失败?
- python - 无法为具有值 ['type'] 的端点 'topic' 构建 url。你的意思是“topic_func”吗?
- ruby-on-rails - 未预编译资产时 Rails 5.2 服务器挂起
- python - mypy:在装饰器中更新的类签名
- django - Django:在 ListView 中定义自定义字段
- certificate - 如何更改由证书颁发机构请求证书创建的证书的有效期以上传到开发者帐户