Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 711
Runner Bean Avatar asked Oct 02 '16 09:10

Runner Bean


People also ask

How do you solve a DataFrame object has no attribute?

Fix error while creating the dataframe To create dataframe we need to use DataFrame(). If we use dataframe it will throw an error because there is no dataframe attribute in pandas. The method is DataFrame(). We need to pass any dictionary as an argument.

What is a pandas index object?

pandas. Index is a basic object that stores axis labels for all pandas objects. DataFrame is a two-dimensional data structure, immutable, heterogeneous tabular data structure with labeled axis rows, and columns.

What are the objects in pandas?

At the very basic level, Pandas objects can be thought of as enhanced versions of NumPy structured arrays in which the rows and columns are identified with labels rather than simple integer indices.


1 Answers

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)
like image 75
Nickil Maveli Avatar answered Sep 22 '22 03:09

Nickil Maveli