将Pandas DataFrame中的日期对象列转换为字符串 [英] Convert column of date objects in Pandas DataFrame to strings

查看:2194
本文介绍了将Pandas DataFrame中的日期对象列转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将由datetime64对象组成的列转换为今天11月1日的
01-11-2013的字符串。

How to convert a column consisting of datetime64 objects to a strings that would read 01-11-2013 for today's date of November 1.

I尝试

df['DateStr'] = df['DateObj'].strftime('%d%m%Y')

但是我收到这个错误

AttributeError:'Series'对象没有属性'strftime'

推荐答案

In [6]: df = DataFrame(dict(A = date_range('20130101',periods=10)))

In [7]: df
Out[7]: 
                    A
0 2013-01-01 00:00:00
1 2013-01-02 00:00:00
2 2013-01-03 00:00:00
3 2013-01-04 00:00:00
4 2013-01-05 00:00:00
5 2013-01-06 00:00:00
6 2013-01-07 00:00:00
7 2013-01-08 00:00:00
8 2013-01-09 00:00:00
9 2013-01-10 00:00:00

In [8]: df['A'].apply(lambda x: x.strftime('%d%m%Y'))
Out[8]: 
0    01012013
1    02012013
2    03012013
3    04012013
4    05012013
5    06012013
6    07012013
7    08012013
8    09012013
9    10012013
Name: A, dtype: object

这篇关于将Pandas DataFrame中的日期对象列转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆