0

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])
2
  • 3
    hour is an int, not a function, split is a function Commented Dec 12, 2020 at 0:28
  • You should use df['Datetime'].dt.hour. You don't need to do lambda x: for everything. It is often better to just used the pandas method without it. Same for the split. You should do: df['title'].str.split(':').str[0]) This is fundamental to writing good code with pandas, so it will greatly benefit you if you can keep these tips in mind. Commented Dec 12, 2020 at 0:35

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.