Numpy - loadtxt和使用转换器的日期

时间:2013-09-23 12:22:04

标签: python numpy

我想加载具有以下格式的txt:

20-Sep-13,178.90,185.83,178.56,183.39,13401689
19-Sep-13,170.80,180.47,169.08,177.92,15594568
18-Sep-13,167.07,167.45,164.20,166.22,5439615
17-Sep-13,165.08,168.42,163.36,166.23,5500719

因此我使用以下Python行:

date, closep, highp, lowp, openp, volume = np.loadtxt(stockFile, delimiter=',', unpack=True, converters={0: mdates.strpdate2num('%d-%b-%y')})

但是我收到以下错误:

failed main loop time data '\xef\xbb\xbf20-Sep-13' does not match format '%d-%b-%y'

有谁知道,我做错了什么?

THX, Maecky

1 个答案:

答案 0 :(得分:3)

文本文件包含UTF-8 BOM字符。 numpy.loadtxt不接受encoding,但您可以传递iterable而不是文件名。

请尝试以下操作:

stockFile = '....'


import numpy as np
import matplotlib.dates as mdates
import codecs

with codecs.open(stockFile, encoding='utf-8-sig') as f:
    date, closep, highp, lowp, openp, volume = np.loadtxt(f, delimiter=',', unpack=True, converters={0: mdates.strpdate2num('%d-%b-%y')})