简体   繁体   中英

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?

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)

solution
use the datetime accessor dt

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM