Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: extracting datetime to year, month, and day result in float

My data has a datetime index like this 2016-11-05 23:40:00.
I want to extract the datetime elements into three new columns of the year, month, and day. I use the following

import datetime as dt
df['year'] = df.index.year
df['month'] = df.index.month
df['day'] = df.index.day

But the results are in float

year    month   day
2016.0  11.0    5.0

I want

year    month   day
2016    11      5

Any help is appreciated.

like image 378
k.ko3n Avatar asked May 29 '19 09:05

k.ko3n


1 Answers

I think reason for floats are missing values, so if use pandas 0.24+ is possible use Nullable Integer Data Type:

df['year'] = df.index.year.astype('Int64')
df['month'] = df.index.month.astype('Int64')
df['day'] = df.index.day.astype('Int64')
like image 120
jezrael Avatar answered Nov 29 '22 10:11

jezrael