Python Pandas - Index' 对象没有属性 'hour'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39815625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Pandas - Index' object has no attribute 'hour'
提问by Runner Bean
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
但我试图使用以下代码减少制作“小时”列的需要
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?
有人知道怎么做吗?
回答by Nickil Maveli
Approach 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:
方法二:
Use axis=0
which computes along the row-index.
使用axis=0
which 沿行索引计算。
df['c'] = df.apply(lambda x: circadian(x.index.hour), axis=0)
回答by piRSquared
solution
use the datetime accessor dt
解决方案
使用日期时间访问器dt
df['c'] = df.index.to_series().dt.hour.apply(circadian)