python - 从 float 到 date Pandas 的多列

标签 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

最佳答案

使用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

关于python - 从 float 到 date Pandas 的多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44255166/

相关文章:

javascript - 如何使用两个日期的 getTime() 正确计算 JS 中的剩余时间?

javascript - 如何从 Javascript 中的数组返回最低日期值和最高日期值?

python - 如何删除 DataFrame 字符串中的特殊字符(例如 ",")?

python - 在传递给 apply() 的自定义函数中访问先前计算的结果

python - 将嵌套 json 解压到数据框中的有效方法

Python:从 CSV 重命名文件

python - 如何从 child 级联删除到 parent

python - Django 中间件的正确顺序是什么?

python - 实现了自己的 __getattr__;遇到意外错误

java - 如何从 Java 中的日历对象构建日、月、年列表?