将datetime列转换回字符串列? pandas -Python [英] Converting a datetime column back to a string columns? Pandas - Python

查看:152
本文介绍了将datetime列转换回字符串列? pandas -Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将datetime列转换回Pandas数据框中的字符串.

I'm trying to convert a datetime column back to a string in Pandas dataframe.

到目前为止,我的语法是:

the syntax I have so far is:

all_data['Order Day new'] = dt.date.strftime(all_data['Order Day new'], '%d/%m/%Y')

但这会返回错误:

描述符'strftime'需要一个'datetime.date'对象,但收到了一个'Series'.

descriptor 'strftime' requires a 'datetime.date' object but received a 'Series'.

谁能告诉我我要去哪里错了.

Can anyone tell me where I'm going wrong.

推荐答案

如果您使用的是版本0.17.0或更高版本,则可以使用

If you're using version 0.17.0 or higher then you can call this using .dt.strftime which is vectorised:

all_data['Order Day new'] = all_data['Order Day new'].dt.strftime('%Y-%m-%d')

**如果您的熊猫版本早于0.17.0,则必须调用apply并将数据传递给strftime:

** If your pandas version is older than 0.17.0 then you have to call apply and pass the data to strftime:

In [111]:

all_data = pd.DataFrame({'Order Day new':[dt.datetime(2014,5,9), dt.datetime(2012,6,19)]})
print(all_data)
all_data.info()
  Order Day new
0    2014-05-09
1    2012-06-19
<class 'pandas.core.frame.DataFrame'>
Int64Index: 2 entries, 0 to 1
Data columns (total 1 columns):
Order Day new    2 non-null datetime64[ns]
dtypes: datetime64[ns](1)
memory usage: 32.0 bytes

In [108]:

all_data['Order Day new'] = all_data['Order Day new'].apply(lambda x: dt.datetime.strftime(x, '%Y-%m-%d'))
all_data
Out[108]:
  Order Day new
0    2014-05-09
1    2012-06-19
In [109]:

all_data.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 2 entries, 0 to 1
Data columns (total 1 columns):
Order Day new    2 non-null object
dtypes: object(1)
memory usage: 32.0+ bytes

您不能在列上调用strftime,因为它不理解Series作为参数,因此会出现错误

You can't call strftime on the column as it doesn't understand Series as a param hence the error

这篇关于将datetime列转换回字符串列? pandas -Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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