'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.
Solution 1:[1]
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')
Solution 2:[2]
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
Solution 3:[3]
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)
Solution 4:[4]
Or if you have a lot of columns, easiest may well be after all the code for constructing data-frame:
df = df.astype(int)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jezrael |
| Solution 2 | |
| Solution 3 | Zaynul Abadin Tuhin |
| Solution 4 | U12-Forward |
