python - 如何在熊猫中只设置时间时间戳?
问题描述
我有一个数据框df
user timestamp amount
us67 15:59:07 87
us90 17:12:19 10
us12 03:23:16 17
print(df.timestamp[0])
>>> datetime.time(15,59,7)
我想把所有的时间都分成 1 小时的间隔,所以总共有 24 个间隔。但是,我得到一个TypeError
df['timestamp'] = pd.cut(x=df['timestamp'], bins=24)
>>> TypeError: unsupported operand type(s) for +: 'datetime.time' and 'float'
但是,如果日期包含在timestamp
列中,该方法确实有效,但我想忽略日期并只保留时间(以便稍后绘制):
user timestamp amount
us67 2018-04-29 15:59:07.455 87
us90 2018-04-29 17:12:19.128 10
us12 2018-04-29 03:23:16.890 17
print(df.timestamo[0])
>>> Timestamp('2018-04-29 15:59:07.455000')
df['timestamp'] = pd.cut(x=df['timestamp'], bins=24)
使用上面的格式timestamp
,分箱工作。但是我不希望时间戳或间隔中的年份和日期。我只想专注于一天中的时间。
有没有办法timestamp
只使用一天中的时间进行分类?最终,这里的目标是仅使用一天中的时间而不是日期来绘制df
( timestamp
vs. amount
) 的时间序列 - 所以如果有更好的方法可以做到这一点,请提出建议。
解决方案
我会使用我的分箱时间创建一个列dt.hour
所以
df["binned_hours"] = pd.cut(df.timestamp.dt.hour, bins=24)