OP 中的错误是因为在 apply()
中调用了 datetime.datetime.strftime
,但没有传递 datetime/date 参数。应该将 format=
作为单独的参数传递给 apply()
,然后再将其传递给 strftime()
作为格式。
from datetime import datetime
x = dates.apply(datetime.strftime, format='%Y%m%d').astype(int)
如果日期是字符串(而不是datetime/date),那么使用
str.replace()
应该可以完成任务。
x = dates.str.replace('-', '').astype(int)
x = dates.apply(lambda x: x.replace('-', '')).astype(int)
一个有趣的(?)事情值得注意的是,pandas 的
.dt.strftime
和
str.replace
都没有被优化,所以通过
apply()
调用 Python 的
strftime
和
str.replace
实际上比 pandas 的对应方法更快(在
strftime
的情况下,速度要快得多)。
dates = pd.Series(pd.date_range('2020','2200', freq='d'))
%timeit dates.dt.strftime('%Y%m%d')
%timeit dates.apply(datetime.strftime, format='%Y%m%d')
dates = dates.astype(str)
%timeit dates.str.replace('-', '')
%timeit dates.apply(lambda x: x.replace('-', ''))
dates.dt.strftime('%Y%m%d')
吗? - Jon Clementsdatetime
值而不是看起来像datetime
的str
字符串吗? - Eric Ed Lohmardf.dates.apply(lambda x: x.replace("-", ""))
因为数据似乎是字符串格式。 - TYZ