Python Pandas - Index' 对象没有属性 'hour'

Python Pandas - Index' object has no attribute 'hour'

我有一个 pandas 日期框,下面的代码有效

df['hour'] = df.index.hour
df['c'] = df['hour'].apply(circadian)

但我试图减少制作 'hour' 列的需要,使用以下代码

df['c'] = df.apply(lambda x: circadian(x.index.hour), axis=1)

但我收到错误消息

AttributeError: ("'Index' object has no attribute 'hour'", u'occurred at index 2015-09-25 01:00:00')

有人知道怎么做吗?

方法一:

DateTimeIndex 转换为 Series 并使用 apply

df['c'] = df.index.to_series().apply(lambda x: circadian(x.hour))

方法二:

使用 axis=0 沿行索引计算。

df['c'] = df.apply(lambda x: circadian(x.index.hour), axis=0)

解决方案
使用日期时间访问器 dt

df['c'] = df.index.to_series().dt.hour.apply(circadian)