【问题标题】:Force to use DatetimeIndex with Pandas强制在 Pandas 中使用 DatetimeIndex
【发布时间】: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


【解决方案1】:

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)

【讨论】:

    猜你喜欢
    • 2021-05-20
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    • 2017-11-03
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多