gpt4 book ai didi

python - 无法使用numpy loadtxt与python3.6转换日期

转载 作者:行者123 更新时间:2023-12-01 02:31:08 24 4
gpt4 key购买 nike

我的代码如下:

import numpy as np
import matplotlib.dates as mdates

stockFile = 'HistoricalQuotes.csv'

dates, close = np.loadtxt(stockFile, delimiter=',', unpack=True, usecols=(0,1), \
converters = {0: mdates.strpdate2num('%Y-%m-%d')})
print("Dates = ", dates)

和回溯:

Traceback (most recent call last):


File "/Users/zdlzdlxs/Documents/workspace/pynum_practice/part3/simplestats.py", line 7, in <module>
converters = {0: mdates.strpdate2num('%Y-%m-%d')})
File "/Users/zdlzdlxs/Library/Python/3.6/lib/python/site-packages/numpy/lib/npyio.py", line 1024, in loadtxt
items = [conv(val) for (conv, val) in zip(converters, vals)]
File "/Users/zdlzdlxs/Library/Python/3.6/lib/python/site-packages/numpy/lib/npyio.py", line 1024, in <listcomp>
items = [conv(val) for (conv, val) in zip(converters, vals)]
File "/Users/zdlzdlxs/Library/Python/3.6/lib/python/site-packages/matplotlib/dates.py", line 287, in __call__
return date2num(datetime.datetime(*time.strptime(s, self.fmt)[:6]))
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_strptime.py", line 559, in _strptime_time
tt = _strptime(data_string, format)[0]
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_strptime.py", line 329, in _strptime
raise TypeError(msg.format(index, type(arg)))
TypeError: strptime() argument 0 must be str, not <class 'bytes'>

我尝试在 stackoverflow 中找到解决方案,但失败了。谁能帮我正确转换日期时间?非常感谢。

最佳答案

这个日期转换器需要一个常规字符串,在 Py3 中是 unicode。但是 loadtxt 将文本加载为字节串:

In [12]: mdates.strpdate2num('%Y-%m-%d')(b'1999-01-31')
---------------------------------------------------------------------------
....
TypeError: strptime() argument 0 must be str, not <class 'bytes'>

修改转换器来解码字节串应该可以解决这个问题:

In [13]: fn = lambda astr: mdates.strpdate2num('%Y-%m-%d')(astr.decode())

In [14]: fn(b'1999-01-01')
Out[14]: 729755.0

在loadtxt中测试:

In [15]: txt=b"""1999-01-01
...: 2000-03-03
...: 2015-12-12
...: """

In [16]: np.loadtxt(txt.splitlines(), converters={0:fn})
Out[16]: array([ 729755., 730182., 735944.])

关于python - 无法使用numpy loadtxt与python3.6转换日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46814724/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com