我正在尝试使用 numpy loadtxt 将 csv 文件加载到数组中。但我似乎无法正确加载日期时间。
下面演示了正在发生的事情。我做错了什么吗?
>>> s = StringIO("05/21/2007,03:27")
>>> np.loadtxt(s, delimiter=",", dtype={'names':('date','time'), 'formats':('datetime64[D]', 'datetime64[m]')})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/lib/npyio.py", line 796, in loadtxt
items = [conv(val) for (conv, val) in zip(converters, vals)]
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/lib/npyio.py", line 573, in <lambda>
return lambda x: int(float(x))
ValueError: invalid literal for float(): 05/21/2007
最佳答案
您还需要添加转换器,例如:
from matplotlib.dates import strpdate2num
...
np.loadtxt(s, delimiter=",", converters={0:strpdate2num('%m/%d/%Y'), 1:...}, dtype= ...
当 numpy 看到你的 dtype 格式为 datetime[64] 时,它准备输出一个 numpy.datetime64 类型的列。 numpy.datetim64 是 numpy.integer 的子类,loadtxt 准备将该列作为整数处理,具有以下内容:
def _getconv(dtype):
typ = dtype.type
if issubclass(typ, np.bool_):
return lambda x: bool(int(x))
if issubclass(typ, np.uint64):
return np.uint64
if issubclass(typ, np.int64):
return np.int64
if issubclass(typ, np.integer):
return lambda x: int(float(x))
...
在 numpyio 的第 796 行开始尝试转换时:
items = [conv(val) for (conv, val) in zip(converters, vals)]
它尝试使用lambda x: int(float(x))
来处理输入。执行此操作时,它会尝试将您的日期 (05/27/2007) 转换为 float 并逐渐消失。上面的转换函数 strpdate2num 会将日期转换为数字表示。
关于Python numpy loadtxt 因日期时间而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16324440/