Python 将日期列从序号转换为标准日期格式-熊猫
我必须将一列日期从整数/日期格式转换为日期格式d-m-Y。示例:Python 将日期列从序号转换为标准日期格式-熊猫,python,pandas,date,integer,calculated-columns,Python,Pandas,Date,Integer,Calculated Columns,我必须将一列日期从整数/日期格式转换为日期格式d-m-Y。示例: 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
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
预期:
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
datetime
fromordinal
应该有帮助
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)
只需
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]
你可以用这个
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
更好的方法是
df['V1']=df['V1']。应用(dt.datetime.fromordinal).dt.strftime(“%d-%m-%Y”)
以获得所需的日期时间format@yatudate.fromordinal
将int
作为输入