I have a pandas df with a year column. I want to get the last day of that year. For example: 2020 –> 2020/12/31
I tried:
data['Date']=datetime.date(year=data['Year'].astype(int), month=12, day=31)
but I get this error: “cannot convert the series to <class ‘int’> “
What am I doing wrong? Thanks
PS I realized I could just do:
data['Date']=data['Year']+"/12/31" data['Date']=pd.to_datetime(data['Date'])
but I’m still wondering what was wrong in my previous code
Advertisement
Answer
Datetime.date
works with single entries one at a time. When using data['year'].astype(int)
you’re trying to pass an Series as an argument and not a single value (as it’s expected).
For that to work, it’d be something like
data['Date']= data['Year'].apply(lambda x:datetime.date(year=x, month=12, day=31))
But it’s somewhat inefficient, the second way you suggested would be faster.