Convert a column of dates from ordinal numbers to the standard date format - pandas

假装没事ソ 提交于 2021-02-05 09:29:17

问题


I have to convert a column of dates from the integer/date format to the date format d-m-Y. Example:

import pandas as pd
col1 = [737346, 737346, 737346, 737346, 737059, 737346]
col2 = ['cod1', 'cod2', 'cod3', 'cod4', 'cod1', 'cod2']
dict = {'V1' : col1, 'V2' : col2}   
df = pd.DataFrame.from_dict(dict)

df

       V1    V2
0  737346  cod1
1  737346  cod2
2  737346  cod3
3  737346  cod4
4  737059  cod1
5  737346  cod2

expected:

df
           V1    V2
0  14-10-2019  cod1
1  14-10-2019  cod2
2  14-10-2019  cod3
3  14-10-2019  cod4
4  31-12-2018  cod1
5  14-10-2019  cod2

回答1:


datetime fromordinal should help.

import datetime as dt

col1 = [737346, 737346, 737346, 737346, 737059, 737346]
col2 = ['cod1', 'cod2', 'cod3', 'cod4', 'cod1', 'cod2']
dd = {'V1' : col1, 'V2' : col2}   
df = pd.DataFrame.from_dict(dd)

df['V1'] = df['V1'].apply(dt.datetime.fromordinal)



回答2:


Just pandas Timestamp.fromordinal

df.V1.map(pd.Timestamp.fromordinal)
Out[511]: 
0   2019-10-14
1   2019-10-14
2   2019-10-14
3   2019-10-14
4   2018-12-31
5   2019-10-14
Name: V1, dtype: datetime64[ns]



回答3:


You can use date.fromordinal for this.

from datetime import datetime as dt

df['V1'] = df.V1.apply(lambda x: dt.fromordinal(x)).dt.strftime('%d-%m-%Y')

print(df)
           V1    V2
0  14-10-2019  cod1
1  14-10-2019  cod2
2  14-10-2019  cod3
3  14-10-2019  cod4
4  31-12-2018  cod1
5  14-10-2019  cod2


来源:https://stackoverflow.com/questions/55224227/convert-a-column-of-dates-from-ordinal-numbers-to-the-standard-date-format-pan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!