Python Forum
Cannot convert the series to <class 'int'> when trying to create new dataframe column
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Cannot convert the series to <class 'int'> when trying to create new dataframe column
#1
Hi all,

I have a dataframe df2 with a 'DATE' column that starts with 17169 in row 2. I'm trying to create a new column with a human readable format:

This...

df2['Human Date'] = datetime.utcfromtimestamp(17169*86400).strftime('%Y-%m-%d')
...returns '2017-01-03'. Why doesn't this...

df2['Human Date'] = datetime.utcfromtimestamp(df2['DATE']*86400).strftime('%Y-%m-%d')
...create a new column and populate based on the same row of the 'DATE' column? Instead, it gives the TypeError shown in the thread subject.
Reply
#2
Can anyone answer this? Thanks!
Reply
#3
This works:

df2['Human Date'] = pd.to_datetime(df2['DATE'],unit='D')
This also works:

df2.insert(1,'Human Date',pd.to_datetime(df2['DATE'],unit='D'))
I'd still like to know why my initial attempt led to the TypeError. Thanks!
Reply
#4
datetime.utcfromtimestamp() expects a float, not a Series. I don't know why the message complains about<class 'int'>.

What you want to do is apply the datetime.utcfromtimestamp() function to each item in the series. For that you use "apply".
import pandas as pd
from datetime import datetime

df2 = pd.DataFrame({"DATE":[17169, 17200]})
df2['DATESTR'] = df2['DATE'].apply(lambda t: datetime.utcfromtimestamp(t*86400).strftime('%Y-%m-%d'))
print(df2)
Output:
DATE DATESTR 0 17169 2017-01-03 1 17200 2017-02-03
Mark17 likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How does this code create a class? Pedroski55 3 135 Yesterday, 04:38 PM
Last Post: Pedroski55
  Adding PD DataFrame column bsben 2 299 Mar-08-2024, 10:46 PM
Last Post: deanhystad
  Python Alteryx QS-Passing pandas dataframe column inside SQL query where condition sanky1990 0 730 Dec-04-2023, 09:48 PM
Last Post: sanky1990
  Convert dataframe from str back to datafarme Creepy 1 621 Jul-07-2023, 02:13 PM
Last Post: snippsat
  Difference one column in a dataframe Scott 0 637 Feb-10-2023, 08:41 AM
Last Post: Scott
  Create new dataframe from old dataframe arvin 3 961 Jan-31-2023, 01:23 PM
Last Post: jefsummers
  splitting a Dataframe Column in two parts nafshar 2 951 Jan-30-2023, 01:19 PM
Last Post: nafshar
  create new column based on condition arvin 12 2,227 Dec-13-2022, 04:53 PM
Last Post: jefsummers
  How do you create a scatterplot of dataframe using matplotlib? asdad 2 856 Dec-07-2022, 04:53 PM
Last Post: Larz60+
  How to assign a value to pandas dataframe column rows based on a condition klllmmm 0 828 Sep-08-2022, 06:32 AM
Last Post: klllmmm

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020