python - pd.to_datetime 上的未知字符串格式

标签 python python-3.x pandas string datetime

我有一个包含日期列的数据集:

cod           date              value 
0   1O8        2015-01-01 00:00:00    2.1
1   1O8        2015-01-01 01:00:00    2.3
2   1O8        2015-01-01 02:00:00    3.5
3   1O8        2015-01-01 03:00:00    4.5
4   1O8        2015-01-01 04:00:00    4.4
5   1O8        2015-01-01 05:00:00    3.2
6   1O9        2015-01-01 00:00:00    1.4
7   1O9        2015-01-01 01:00:00    8.6
8   1O9        2015-01-01 02:00:00    3.3
10  1O9        2015-01-01 03:00:00    1.5
11  1O9        2015-01-01 04:00:00    2.4
12  1O9        2015-01-01 05:00:00    7.2

日期列的dtypes是一个对象,用于在我需要将日期列类型更改为数据时间后应用一些功能。我尝试了不同的解决方案,例如:

pd.to_datetime(df['date'], errors='raise', format ='%Y-%m-%d HH:mm:ss')
pd.to_datetime(df['date'], errors='coerce', format ='%Y-%m-%d HH:mm:ss')
df['date'].apply(pd.to_datetime, format ='%Y-%m-%d HH:mm:ss')

但错误只是一样的:

TypeError: Unrecognized value type: <class 'str'>
ValueError: Unknown string format

直接的事情是,如果我将 te 函数应用于数据集样本,该函数会正确响应,但如果我将它应用于所有数据集,则会退出错误。数据中存在缺失值,所有值的 dtype 都相同。

我该如何修复这个错误?

最佳答案

存在三个问题:

  1. pd.to_datetimepd.Series.apply 无法正常工作,因此您的解决方案不会修改您的系列。转换后分配回来。
  2. 您的第三个解决方案需要 errors='coerce' 来保证没有错误。
  3. 对于时间组件,您需要使用以 % 开头的特定字符串格式。

所以你可以使用:

df = pd.DataFrame({'date': ['2015-01-01 00:00:00', '2016-12-20 15:00:20',
                            '2017-08-05 00:05:00', '2018-05-11 00:10:00']})

df['date'] = pd.to_datetime(df['date'], errors='coerce', format='%Y-%m-%d %H:%M:%S')

print(df)

                  date
0  2015-01-01 00:00:00
1  2016-12-20 15:00:20
2  2017-08-05 00:05:00
3  2018-05-11 00:10:00

在这个特定的例子中,格式是标准的,可以省略:

df['date'] = pd.to_datetime(df['date'], errors='coerce')

关于python - pd.to_datetime 上的未知字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53537443/

相关文章:

python-3.x - 如何停止我的功能?

python-3.x - key 错误 : "None of [Int64Index([1960, 1961, 1962, 1963, 1964], dtype=' int6 4')] are in the [columns]"

c++ - 请求有关执行 IPC/事件捕获的建议

python - 在 python 中,在较大的字符串中优雅地扩展某些子字符串

python - Linux Only 'ascii' 编解码器无法对位置 3 : ordinal not in range(128) 中的字符 u'\u0161' 进行编码

mysql - 如何使用 Python 或 SQL 中的联接或任何其他操作合并两个数据集/表

python - 如何使用 pandas 创建像索引这样的分层目录?

sql - Pandas DataFrame.to_sql() 函数是否需要后续的 commit()?

python - 我从本地时间转换为 UTC 有什么问题

python - 连接多个 .fasta 文件