You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用numpy.loadtxt加载日期时遇指定NumPy datetime错误求助

解决NumPy加载日期文本的报错与matplotlib导入问题

1. 修复Cannot create a NumPy datetime other than NaT with generic units错误

这个报错的核心原因有两个:一是datetime64 dtype必须指定具体时间单位(比如天[D]、秒[s]),不能用泛型的datetime64;二是np.loadtxt不会自动将字符串解析为日期类型,需要配合转换器处理。

修改后的可运行代码:

import numpy as np
from io import StringIO

# 定义日期转换器:将字节字符串转为datetime64[D]类型
def parse_date(s):
    return np.datetime64(s.decode('utf-8'), 'D')

# 明确指定datetime64的时间单位为天[D]
dt = np.dtype({
    'names': ['name', 'height', 'year'],
    'formats': ['U55', 'f4', 'datetime64[D]']
})

I = StringIO('Alice,1.75,2000-08-03')
# 给第3列(索引为2)绑定日期转换器
txt = np.loadtxt(I, dtype=dt, delimiter=',', converters={2: parse_date})

2. 更简便的替代方案:使用np.genfromtxt

np.genfromtxt对结构化数据的日期解析更友好,无需额外定义转换器,只要指定正确的datetime64单位即可:

import numpy as np
from io import StringIO

dt = np.dtype({
    'names': ['name', 'height', 'year'],
    'formats': ['U55', 'f4', 'datetime64[D]']
})
I = StringIO('Alice,1.75,2000-08-03')
txt = np.genfromtxt(I, dtype=dt, delimiter=',')

3. 关于matplotlib strpdate2num导入失败的问题

strpdate2num在matplotlib 3.1及以后版本已被官方弃用,因此会出现导入失败的情况。如果一定要使用matplotlib的日期转换工具,可改用matplotlib.dates.datestr2num,但更推荐用NumPy原生的datetime64处理逻辑,避免不必要的依赖。


内容的提问来源于stack exchange,提问作者Étalo Reis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 18:05:18