Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 替换时间戳中的小时和分钟_Python_Pandas_Timestamp - Fatal编程技术网

Python 替换时间戳中的小时和分钟

Python 替换时间戳中的小时和分钟,python,pandas,timestamp,Python,Pandas,Timestamp,问题:我有以下数据帧。基于某个时间,我想用t_hour和t_min替换小时和分钟,以获得目标时间 some_time target_time t_hour t_min 0 2020-09-01 19:00:58.0000 2020-09-01 20:00:00.0000 20 00 1 2020-10-31 14:44:00.0000 2020-10-31

问题:我有以下数据帧。基于某个时间,我想用t_hour和t_min替换小时和分钟,以获得目标时间

  some_time                    target_time                    t_hour       t_min
0 2020-09-01 19:00:58.0000     2020-09-01 20:00:00.0000       20           00
1 2020-10-31 14:44:00.0000     2020-10-31 17:45:00.0000       17           45
尝试

data['target_time'] = data['start_time'].replace(hour=data['t_hour'],minute=data['t_min'], second=0))
这是行不通的

错误:

TypeError: replace() got an unexpected keyword argument 'hour'

非常感谢您的帮助!谢谢

我自由地让这个例子更具说明性;给定一个数据帧,如

data
           start_time target_time  t_hour  t_min
0 2020-09-01 19:00:58  2020-09-01      20      0
1 2020-10-31 14:44:00  2020-10-31      17     45
首先确保datetime列都转换为dtype datetime[64]。然后,您可以应用自定义功能来实现您的目标,例如

def insert_time(row):
    return row['start_time'].replace(hour=row['t_hour'], minute=row['t_min'], second=0)

data['target_time'] = data.apply(lambda r: insert_time(r), axis=1)
这会给你

data
           start_time         target_time  t_hour  t_min
0 2020-09-01 19:00:58 2020-09-01 20:00:00      20      0
1 2020-10-31 14:44:00 2020-10-31 17:45:00      17     45

不幸的是,似乎没有一个内置的“矢量化”选项来访问时间戳的replace方法。我想你得用一个迭代解。