[英]Python Pandas - Index' object has no attribute 'hour'
I have a pandas dateframe and the following code works 我有一个pandas日期框架,以下代码可以正常工作
df['hour'] = df.index.hour
df['c'] = df['hour'].apply(circadian)
but i was trying to reduce the need to make a 'hour' coloumn, using the following code 但我试图使用以下代码减少制作'小时'coloumn的需要
df['c'] = df.apply(lambda x: circadian(x.index.hour), axis=1)
but I get the error message 但我收到错误信息
AttributeError: ("'Index' object has no attribute 'hour'", u'occurred at index 2015-09-25 01:00:00')
anyone know how to do this? 有人知道怎么做吗?
Approach 1: 方法1:
Convert the DateTimeIndex
to Series
and use apply
. 将
DateTimeIndex
转换为Series
并使用apply
。
df['c'] = df.index.to_series().apply(lambda x: circadian(x.hour))
Approach 2: 方法2:
Use axis=0
which computes along the row-index. 使用
axis=0
,它沿行索引计算。
df['c'] = df.apply(lambda x: circadian(x.index.hour), axis=0)
solution 解
use the datetime accessor dt
使用datetime访问器
dt
df['c'] = df.index.to_series().dt.hour.apply(circadian)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.