将 Pandas DataFrame 中的日期列转换为字符串

56

如何将由datetime64对象组成的列转换为字符串,以便读作“01-11-2013”,以表示今天的日期是11月1日。

我尝试过

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

但我遇到了这个错误

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

3个回答

89

截至版本17.0,您可以使用dt访问器进行格式化:

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

1
在使用assign时,发现这个非常有用,例如: (df .query('我的查询条件在这里') .assign(month = lambda x: x['date'].dt.strftime('%Y-%m')) ) - measureallthethings
这个方法会比 df['A'].apply(lambda x: x.strftime('%d%m%Y')) 快一点。 对于 230k 列,耗时为 1.3 秒,而后者大约需要 1.9 秒。 - Pengju Zhao
1
对于更大的数据集,dt访问器应该会更快,因为apply本质上是一个for循环,而dt使用基于C的优化,如果我没记错的话。 - Kamil Sindi
我因这个问题收到了警告:正在尝试在DataFrame的切片副本上设置值。 - Chen-CN
1
有时需要进行日期时间转换,例如:df['DateObj'].astype('datetime64[ns]').dt.strftime('%Y') - PeJota

51
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

0

如果您首先将其设置为索引,则可以直接使用它。然后,您实际上是传递一个'DatetimeIndex'对象而不是'Series'

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接