强制将 DatetimeIndex 与 Pandas 一起使用

Force to use DatetimeIndex with Pandas

我有以下 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

我的objective是根据每天发生的记录构建一个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' object has no attribute 'year'

如何强制数据框使用索引列作为 DatetimeIndex? 我找到了 this 有趣的答案,但我不明白如何将 df = df.set_index(pd.DatetimeIndex(df['b'])) 用于现有索引而不是新列。

calmap 文档指出它将默认为每日总和,因此您不必将日期时间字段更改为日期字段。只需将 unplug_hourDateTime 列更改为 datetime index,如下所示。我的示例使用方法链接,这意味着一切都在 1 go 中完成:

df_calmap = (df
    .assign(unplug_hourDateTime=pd.DatetimeIndex(df['unplug_hourDateTime']))
    .groupby('unplug_hourDateTime')
    .size()
    .to_frame('count')
)

calmap.calendarplot(df_calmap['count'])

当然,你也可以使用 Josh Friedlander 的精彩回答:

df.index = pd.DateTimeIndex(df.index)