Yash
Yash

Reputation: 369

Python lambda function error when used with brackets

I have a pandas data frame with 'Datetime' column containing timestamp information, I want to extract the hour information from the 'Datetime' column and add it to the hour column of the data frame.

I am confused since my code works if I write the lambda function without the braces

df['Datetime'].apply(lambda x: x.hour)

but, when I try this code instead

df['Datetime'].apply(lambda x: x.hour**()**)

I get the error "TypeError: 'int' object is not callable".

On the other hand when I use split function with lambda expression, it works completely fine with the braces -

df['Reasons'] = df['title'].apply(lambda x: x.split(':')[0])

Upvotes: 0

Views: 217

Answers (1)

Rajat Mishra
Rajat Mishra

Reputation: 3770

As mentioned by @Dani Mesejo, hour is an attribute of the datetime object. Hence it is working fine without brackets. Once you add brackets, it assumes the hour is a function and so you are getting that error.

You can read more about datetime object in its documentation

Upvotes: 1

Related Questions