首页 > 解决方案 > numpy 分配给具有浮点数的日期的 dtype 数组导致“无法将字符串转换为浮点数:'2017-01-01T01:01:01'”错误

问题描述

为什么以下 numpy 数组赋值会导致 ValueError: 'could not convert string to float: '2017-01-01T01:01:01''

import numpy as np
r=['2017-01-01T01:01:01','61.380001068115234']
t = np.dtype([('d', 'datetime64[s]'), ('o', 'f4')])
s = np.array(r, dtype=t)

python 3.8.2,Windows 10,numpy 1.19.1。

标签: pythonarraysnumpydatetimedtype

解决方案


您将数据类型定义为 datetime 和 float 的元组,因此数组中的每个项目都应该是这样的元组。

这是正确的:

np.array([('2017-01-01T01:01:01', '61.380001068115234')], dtype=t)

如果数组中有多个项目,它将如下所示:

np.array([
    ('2017-01-01T01:01:01', '61.380001068115234'),
    ('2017-01-02T01:01:01', '62.380001068115234'),
    ('2017-01-03T01:01:01', '63.380001068115234'),
    ], dtype=t)

推荐阅读