Runner Bean Runner Bean - 10 months ago 88
Python Question

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

I have a pandas dateframe and the following code works

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?

Answer Source

Approach 1:

Convert the DateTimeIndex to Series and use apply.

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

Approach 2:

Use axis=0 which computes along the row-index.

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