假设我有以下数据集:
我将如何创建一个新的专栏,作为时间的一部分?
例如,下面的代码适用于个别时间,但我无法将其概括为 pandas 中的列。
t = datetime.strptime('9:33:07','%H:%M:%S')
print(t.hour)
最佳答案
使用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
如果想在 TIME
列中使用 datetime
可以分配回去:
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
关于python - 从 Pandas 的时间列中提取小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53045867/