将日期时间列转换回字符串列?熊猫 - Python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28694025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting a datetime column back to a string columns? Pandas - Python
提问by Colin O'Brien
I'm trying to convert a datetime column back to a string in Pandas dataframe.
我正在尝试将日期时间列转换回 Pandas 数据框中的字符串。
the syntax I have so far is:
我到目前为止的语法是:
all_data['Order Day new'] = dt.date.strftime(all_data['Order Day new'], '%d/%m/%Y')
but this returns the error:
但这会返回错误:
descriptor 'strftime' requires a 'datetime.date' object but received a 'Series'.
描述符“strftime”需要“datetime.date”对象,但收到“Series”。
Can anyone tell me where I'm going wrong.
谁能告诉我哪里出错了。
采纳答案by EdChum
If you're using version 0.17.0
or higher then you can call this using .dt.strftime
which is vectorised:
如果您使用的是版本0.17.0
或更高版本,那么您可以使用.dt.strftime
矢量化的方式调用它:
all_data['Order Day new'] = all_data['Order Day new'].dt.strftime('%Y-%m-%d')
** If your pandas version is older than 0.17.0
then you have to call apply
and pass the data to strftime
:
** 如果您的 Pandas 版本比0.17.0
那时旧,您必须调用apply
并将数据传递给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
You can't call strftime
on the column as it doesn't understand Series
as a param hence the error
您不能调用strftime
该列,因为它不能理解Series
为参数,因此错误
回答by Chris
all_data['Order Day new']=all_data['Order Day new'].astype(str)
I think this is more simple, if the date is already in the format you want it in string form.
我认为这更简单,如果日期已经是您想要的字符串形式的格式。