Reputation: 954
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.
Upvotes: 8
Views: 6565
Reputation: 4792
Just use astype
:
import datetime as dt
df['year'] = df.index.year.astype(int)
df['month'] = df.index.month.astype(int)
df['day'] = df.index.day.astype(int)
If there are Nan's then use errors parameter:
df['year'] = df.index.year.astype(int, errors='ignore')
This will return nans for the columns with null index
Upvotes: 4
Reputation: 862681
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')
Upvotes: 11
Reputation: 71580
Or if you have a lot of columns, easiest may well be after all the code for constructing data-frame:
df = df.astype(int)
Upvotes: 0
Reputation: 31993
convert it on int
import datetime as dt
df['year'] = int(df.index.year)
df['month'] = int(df.index.month)
df['day'] = int(df.index.day)
Upvotes: 3