Numpy 使用Matplotlib'时出现类型错误;s strpdate2num与Python 3.2
在我当前的项目中,我希望使用以下代码将一些实验数据从文本文件读入Python:Numpy 使用Matplotlib'时出现类型错误;s strpdate2num与Python 3.2,numpy,python-3.x,matplotlib,Numpy,Python 3.x,Matplotlib,在我当前的项目中,我希望使用以下代码将一些实验数据从文本文件读入Python: import numpy as np from matplotlib.dates import strpdate2num data = np.recfromtxt('example.txt', comments='#', delimiter=';', names=('time', 't_ref', 't_s', '
import numpy as np
from matplotlib.dates import strpdate2num
data = np.recfromtxt('example.txt',
comments='#',
delimiter=';',
names=('time', 't_ref', 't_s', 't_amb1', 't_amb2', 't_amb3')
,converters={'time': strpdate2num('"%d.%m.%Y %H:%M:%S"')}
)
使用example.txt
看起来像
"04.10.2012 08:15:27";14.4;16;12.78;12.65;12.52
"04.10.2012 08:15:37";14.4;16;12.78;12.65;12.5
"04.10.2012 08:15:47";14.4;16;12.78;12.62;12.5
"04.10.2012 08:15:57";14.4;15.9;12.78;12.65;12.52
...
在Python2.7中,一切都很好,但是当我尝试传输3.2中的代码时,我从strpdate2num()
中得到一个TypeError
TypeError: strptime() argument 0 must be str, not <class 'bytes'>
TypeError:strtime()参数0必须是str,而不是
我对Python相当陌生,但我的理论是NumPy以某种方式在内部将时间数组存储为字节而不是字符串,这与自Python 3以来对两者的更严格处理相冲突
长话短说,你知道原因是什么吗?如何解决这个问题?这里有一个解决方法:
import numpy as np
import matplotlib.dates as mdates
def bytedate2num(fmt):
def converter(b):
return mdates.strpdate2num(fmt)(b.decode('ascii'))
return converter
date_converter = bytedate2num("%d.%m.%Y %H:%M:%S")
data = np.recfromtxt('example.txt',
comments='#',
delimiter=';',
names=('time', 't_ref', 't_s', 't_amb1', 't_amb2', 't_amb3'),
converters={'time': date_converter})
我必须删除示例文本中的引号。(使用python3.4)
工作的变通方法非常好。与此同时,问题似乎已经得到解决。使用
bytepdate2num()
而不是strpdate2num()
对我有效。这应该被标记为正确答案。如前所述,Python 3用户应该像这样导入bytespdate2num:从matplotlib.dates导入bytespdate2num
ValueError: time data '"04.10.2012 08:15:27"' does not match format '%d.%m.%Y %H:%M:%S'