Python/Pandas仅将字符串转换为时间 [英] Python/Pandas convert string to time only
问题描述
我在Python 2.7中具有以下Pandas数据框.
I have the following Pandas dataframe in Python 2.7.
import pandas as pd
trial_num = [1,2,3,4,5]
sail_rem_time = ['11:33:11','16:29:05','09:37:56','21:43:31','17:42:06']
dfc = pd.DataFrame(zip(*[trial_num,sail_rem_time]),columns=['Temp_Reading','Time_of_Sail'])
print dfc
数据框如下所示:
Temp_Reading Time_of_Sail
1 11:33:11
2 16:29:05
3 09:37:56
4 21:43:31
5 17:42:06
此数据框来自* .csv文件.我使用Pandas作为Pandas数据框读取* .csv文件.当我使用print dfc.dtypes
时,它向我显示列Time_of_Sail
的数据类型为object
.我想将此列转换为datetime
数据类型,但我只想要时间部分-我不想要年,月,日.
This dataframe comes from a *.csv file. I use Pandas to read in the *.csv file as a Pandas dataframe. When I use print dfc.dtypes
, it shows me that the column Time_of_Sail
has a datatype object
. I would like to convert this column to datetime
datatype BUT I only want the time part - I don't want the year, month, date.
我可以尝试:
dfc['Time_of_Sail'] = pd.to_datetime(dfc['Time_of_Sail'])
dfc['Time_of_Sail'] = [time.time() for time in dfc['Time_of_Sail']]
但是问题是,当我运行print dfc.dtypes
时,它仍然显示列Time_of_Sail
是object
.
but the problem is that the when I run print dfc.dtypes
it still shows that the column Time_of_Sail
is object
.
是否可以将此列转换为只有时间的日期时间格式?
Is there a way to convert this column into a datetime format that only has the time?
其他信息:
要创建上述数据框并输出,这也可以:
To create the above dataframe and output, this also works:
import pandas as pd
trial_num = [1,2,3,4,5]
sail_rem_time = ['11:33:11','16:29:05','09:37:56','21:43:31','17:42:06']
data = [
[trial_num[0],sail_rem_time[0]],
[trial_num[1],sail_rem_time[1]],[trial_num[2],sail_rem_time[2]],
[trial_num[3],sail_rem_time[3]]
]
dfc = pd.DataFrame(data,columns=['Temp_Reading','Time_of_Sail'])
dfc['Time_of_Sail'] = pd.to_datetime(dfc['Time_of_Sail'])
dfc['Time_of_Sail'] = [time.time() for time in dfc['Time_of_Sail']]
print dfc
print dfc.dtypes
推荐答案
这两行:
dfc['Time_of_Sail'] = pd.to_datetime(dfc['Time_of_Sail'])
dfc['Time_of_Sail'] = [time.time() for time in dfc['Time_of_Sail']]
可以写为:
dfc['Time_of_Sail'] = pd.to_datetime(dfc['Time_of_Sail'],format= '%H:%M:%S' ).dt.time
这篇关于Python/Pandas仅将字符串转换为时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!