浮动到日期的多个列Pandas

时间:2017-05-30 06:39:04

标签: python date pandas

我有一个数据框,数据导入为float64。我已经能够将1列转换为日期,但是当我尝试将其缩放为多个时,我得到:

ValueError: to assemble mappings requires at least that [year, month, day] be 
specified: [day,month,year] is missing 

适用于1列:

df['Col4'] = pd.to_datetime(df['Col4'].astype(str), format = '%Y%m%d')

df.head().dtypes
Out[151]: 
Col1            float64
Col2            object
Col3            float64
Col4     datetime64[ns]
Col5            float64
Col6            float64
dtype: object

我尝试了下面的多列并被拒绝,任何帮助表示赞赏:

"""
df[['Col4', 'Col5']] = pd.to_datetime(df[['Col4' , 'Col5']].astype(str), format = '%Y%m%d')
df.head().dtypes
"""
ValueError: to assemble mappings requires at least that [year, month, day] be specified: [day,month,year] is missing

1 个答案:

答案 0 :(得分:1)

使用apply

cols = ['Col4', 'Col5']
df[cols] = df[cols].apply(lambda x: pd.to_datetime(x.astype(str), format = '%Y%m%d'))

样品:

df = pd.DataFrame({'Col4':[20150101.0, 20150102],
                   'Col5':[20160101.0, 20160102],
                   'Col1':[1,2]})
print (df)
   Col1        Col4        Col5
0     1  20150101.0  20160101.0
1     2  20150102.0  20160102.0

cols = ['Col4', 'Col5']
df[cols] = df[cols].apply(lambda x: pd.to_datetime(x.astype(str), format = '%Y%m%d'))
print (df)
   Col1       Col4       Col5
0     1 2015-01-01 2016-01-01
1     2 2015-01-02 2016-01-02
cols = ['Col4', 'Col5']
df[cols] = df[cols].astype(str).apply(pd.to_datetime, format = '%Y%m%d')
print (df)
   Col1       Col4       Col5
0     1 2015-01-01 2016-01-01
1     2 2015-01-02 2016-01-02