How To Convert A Column Of Numbers Into A Date In A Dataframe In Python
My dataframe contains a column for dates. It looks like this: Index Date 0 12018 1 102018 2 32018 3 122018 4 112019 5 32019 6 4201
Solution 1:
I think to_datetime
with a specified format should be enough:
df['Date'] = pd.to_datetime(df['Date'], format='%m%Y')
print (df)
Index Date
0 0 2018-01-01
1 1 2018-10-01
2 2 2018-03-01
3 3 2018-12-01
4 4 2019-11-01
5 5 2019-03-01
6 6 2019-04-01
print (df.dtypes)
Index int64
Date datetime64[ns]
dtype: object
Thank you @Vivek Kalyanarangan for solution - add strftime
for custom string
format (but lost datetimes):
df['Date'] = pd.to_datetime(df['Date'], format='%m%Y').dt.strftime('%d-%m-%Y')
print (df)
Index Date
0 0 01-01-2018
1 1 01-10-2018
2 2 01-03-2018
3 3 01-12-2018
4 4 01-11-2019
5 5 01-03-2019
6 6 01-04-2019
print (df.dtypes)
Index int64
Date object
dtype: object
print (df['Date'].apply(type))
0 <class 'str'>
1 <class 'str'>
2 <class 'str'>
3 <class 'str'>
4 <class 'str'>
5 <class 'str'>
6 <class 'str'>
Name: Date, dtype: object
Post a Comment for "How To Convert A Column Of Numbers Into A Date In A Dataframe In Python"