【发布时间】:2019-06-01 10:59:13
【问题描述】:
我有以下 Pandas 数据框:
df.head()
输出
id unplug_hourDateTime
0 2018-09-01 01:00:00+02:00
1 2018-03-01 01:00:00+02:00
2 2018-03-01 01:00:00+02:00
3 2018-04-01 01:00:00+02:00
4 2018-04-01 01:00:00+02:00
我的目标是根据每天发生的记录构建一个calmap 图表,因此我需要一个索引为 DatetimeIndex、TimedeltaIndex 或 PeriodIndex 格式的数据框。
我写了以下内容:
df['unplug_Date']=df['unplug_hourDateTime'].map(lambda x : x.date())
df_calmap=df['unplug_Date'].value_counts().to_frame()
df_calmap.head()
输出
unplug_Date
2018-09-20 16562
2018-09-13 16288
2018-09-19 16288
2018-09-12 16092
2018-09-27 16074
乍一看,它看起来是我要找的东西,但如果我使用 Calmap 包,然后执行 calmap.calendarplot(df_calmap) 我会收到一个错误,我认为这是由于索引的格式造成的。
AttributeError: 'Index' 对象没有属性 'year'
如何强制数据框将索引列用作 DatetimeIndex?
我找到了this 有趣的答案,但我不明白如何将df = df.set_index(pd.DatetimeIndex(df['b'])) 与现有索引而不是新列一起使用。
【问题讨论】:
-
df.index = pd.DateTimeIndex(df.index)呢? -
它工作,谢谢! (我用的是 DatetimeIndex 方法而不是 DateTimeIndex)
标签: python python-3.x pandas date datetimeindex