【问题标题】:Python Pandas - Index' object has no attribute 'hour'Python Pandas - 索引'对象没有属性'小时'
【发布时间】:2017-02-10 10:54:55
【问题描述】:

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

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

但我试图减少制作“小时”列的需要,使用以下代码

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')

有人知道怎么做吗?

【问题讨论】:

    标签: python pandas apply


    【解决方案1】:

    方法一:

    将DateTimeIndex 转换为Series 并使用apply。

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

    方法2:

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2017-03-06
        • 2015-05-08
        • 1970-01-01
        • 2017-03-14
        • 2019-02-03
        • 2020-09-06
        • 2015-05-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多