如何将由datetime64对象组成的列转换为日期为11月1日的01-11-2013字符串。
我试过了
df['DateStr'] = df['DateObj'].strftime('%d%m%Y')但我知道这个错误
AttributeError:“串联”对象没有属性“strftime”
发布于 2013-11-02 02:33:53
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发布于 2015-11-28 03:31:25
从17.0版开始,您可以使用dt访问器进行格式化:
df['DateStr'] = df['DateObj'].dt.strftime('%d%m%Y')发布于 2022-06-07 17:26:52
它直接工作,如果您首先设置为索引。从本质上说,您传递的是“DatetimeIndex”对象,而不是“系列”
df = df.set_index('DateObj').copy()
df['DateStr'] = df.index.strftime('%d%m%Y')https://stackoverflow.com/questions/19738169
复制相似问题