【发布时间】:2019-09-22 10:08:00
【问题描述】:
假设我有以下数据集:
我将如何创建一个新列,作为时间的小时?
例如,下面的代码适用于个别时间,但我无法将其推广到 pandas 中的列。
t = datetime.strptime('9:33:07','%H:%M:%S')
print(t.hour)
【问题讨论】:
-
你可以使用 lambda 函数:
df['col'] = df['time'].apply(lambda x: x.hour) -
这会导致错误:AttributeError: 'str' object has no attribute 'hour'
-
那是因为你的时间列是一个 str 而不是日期时间你需要先做
df['time'] = pd.to_datetime(df['time']) -
啊,当然,谢谢克里斯。