PyR*_*red 5 python datetime pandas
我有一个数据框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)
Run Code Online (Sandbox Code Playgroud)
我想将所有时间分成 1 小时间隔,因此总共 24 个间隔。但是,我得到了TypeError
df['timestamp'] = pd.cut(x=df['timestamp'], bins=24)
>>> TypeError: unsupported operand type(s) for +: 'datetime.time' and 'float'
Run Code Online (Sandbox Code Playgroud)
但是,如果日期包含在列中,该方法确实有效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)
Run Code Online (Sandbox Code Playgroud)
使用上面的格式timestamp
,可以进行分箱。但是我不希望时间戳或间隔中包含年份和日期。我只想关注一天中的某个时间。
有没有办法timestamp
只使用一天中的某个时间进行垃圾箱?最终的目标是仅使用一天中的小时而不是日期来绘制df
( timestamp
vs. amount
) 的时间序列 - 因此,如果有更好的方法可以做到这一点,请提出建议。
我将使用我的分箱时间创建一个列dt.hour
所以
df["binned_hours"] = pd.cut(df.timestamp.dt.hour, bins=24)
Run Code Online (Sandbox Code Playgroud)