MRH*_*arv 2 python datetime pandas
假设我有以下数据集:
我将如何创建一个新的列,该时间是小时?
例如,下面的代码可单独使用,但我无法将其概括为pandas中的一列。
t = datetime.strptime('9:33:07','%H:%M:%S')
print(t.hour)
Run Code Online (Sandbox Code Playgroud)
使用to_datetime与日期时间dt.hour:
df = pd.DataFrame({'TIME':['9:33:07','9:41:09']})
#should be slowier
#df['hour'] = pd.to_datetime(df['TIME']).dt.hour
df['hour'] = pd.to_datetime(df['TIME'], format='%H:%M:%S').dt.hour
print (df)
TIME hour
0 9:33:07 9
1 9:41:09 9
Run Code Online (Sandbox Code Playgroud)
如果想datetime在列中使用s TIME可以分配回来:
df['TIME'] = pd.to_datetime(df['TIME'], format='%H:%M:%S')
df['hour'] = df['TIME'].dt.hour
print (df)
TIME hour
0 1900-01-01 09:33:07 9
1 1900-01-01 09:41:09 9
Run Code Online (Sandbox Code Playgroud)