将 pandas 中的日期时间列 yyyy-mm-dd 转换为 YYYYMMDD。

14

我有一个包含日期时间列的数据框,格式为yyyy-mm-dd。我想将其转换为整数格式yyyymmdd。当我尝试时:

x=dates.apply(dt.datetime.strftime('%Y%m%d')).astype(int)

我一直收到一个错误:
TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'

如果我尝试传递一个数组,这个方法就不起作用了。我知道如果只传递一个元素,它会转换成功,但有没有更符合Python风格的方法呢?我尝试使用lambda函数,但也没有成功。


1
你试过使用 dates.dt.strftime('%Y%m%d') 吗? - Jon Clements
你确定该列包含的是 datetime 值而不是看起来像 datetimestr 字符串吗? - Eric Ed Lohmar
你试过这个吗:df.dates.apply(lambda x: x.replace("-", "")) 因为数据似乎是字符串格式。 - TYZ
2个回答

23
如果你的列是字符串类型的,你需要先使用 `pd.to_datetime'。
df['Date'] = pd.to_datetime(df['Date'])

然后,使用.dt datetime访问器和strftime函数:

df = pd.DataFrame({'Date':pd.date_range('2017-01-01', periods = 60, freq='D')})

df.Date.dt.strftime('%Y%m%d').astype(int)

或者使用Lambda函数:

df.Date.apply(lambda x: x.strftime('%Y%m%d')).astype(int)

输出:

0     20170101
1     20170102
2     20170103
3     20170104
4     20170105
5     20170106
6     20170107
7     20170108
8     20170109
9     20170110
10    20170111
11    20170112
12    20170113
13    20170114
14    20170115
15    20170116
16    20170117
17    20170118
18    20170119
19    20170120
20    20170121
21    20170122
22    20170123
23    20170124
24    20170125
25    20170126
26    20170127
27    20170128
28    20170129
29    20170130
30    20170131
31    20170201
32    20170202
33    20170203
34    20170204
35    20170205
36    20170206
37    20170207
38    20170208
39    20170209
40    20170210
41    20170211
42    20170212
43    20170213
44    20170214
45    20170215
46    20170216
47    20170217
48    20170218
49    20170219
50    20170220
51    20170221
52    20170222
53    20170223
54    20170224
55    20170225
56    20170226
57    20170227
58    20170228
59    20170301
Name: Date, dtype: int32

您还可以将 df ['Date'] .astype(str) .str.replace('-','') .astype(int)df ['Date'] .astype(str) .str.split('-') .str.join('') .astype(int) 添加到您的选项中。 - Bharath M Shetty

0

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)

# using apply
x = dates.apply(lambda x: x.replace('-', '')).astype(int)

一个有趣的(?)事情值得注意的是,pandas 的 .dt.strftimestr.replace 都没有被优化,所以通过 apply() 调用 Python 的 strftimestr.replace 实际上比 pandas 的对应方法更快(在 strftime 的情况下,速度要快得多)。
dates = pd.Series(pd.date_range('2020','2200', freq='d'))

%timeit dates.dt.strftime('%Y%m%d')
# 719 ms ± 41.5 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit dates.apply(datetime.strftime, format='%Y%m%d')
# 472 ms ± 34.5 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

dates = dates.astype(str)

%timeit dates.str.replace('-', '')
# 30.9 ms ± 2.46 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit dates.apply(lambda x: x.replace('-', ''))
# 26 ms ± 183 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

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