我正在尝试使用带有converter参数的numpy.loadtxt从文本文件中读取数据。我有一系列的整数和字符串。代码是:
a, b, c, d, e = np.loadtxt(infile, delimiter = ',', usecols=(0, 2, 5, 8, 9), skiprows = 1,
unpack = True, converters = dict(zip((0, 2, 5, 8, 9), (int, float, float, int, int))))
正确读取数据并正确解压缩,但所有变量(a,b,c,d和e)最终都是浮点数。我在转换器语法中犯了错误吗?
编辑尝试回答
我尝试使用@joris建议的dtype =(int,float,float,int,int):
a,b,c,d,e = np.loadtxt(infile,delimiter = ',', usecols=(0,2,5,8,9), skiprows = 1, unpack = True, dtype = (int,float,float,int,int))
但是我收到以下错误:
41 skiprows = 1,
42 unpack = True,
---> 43 dtype = (int,float,float,int,int))
44
45
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/lib/npyio.pyc in loadtxt(fname, dtype, comments, delimiter, converters, skiprows, usecols, unpack)
665 try:
666 # Make sure we're dealing with a proper dtype
--> 667 dtype = np.dtype(dtype)
668 defconv = _getconv(dtype)
669
TypeError: data type not understood
WARNING: Failure executing file: <forward_NDMMF.py>
我正在使用NumPy v.1.5.1。
答案 0 :(得分:3)
loadtxt
文档表明了这一点
converters
应包含specifically return floats:
转换器:dict,可选
将列号映射到将该列转换为float的函数的字典。例如,如果第0列是日期字符串:converters = {0:datestr2num}。转换器还可用于为缺失数据提供默认值:converters = {3:lambda s:float(s或0)}。默认值:无。
如果您想要整数,则需要使用dtype
关键字来转换浮点数。
>>> numpy.loadtxt('th.txt', delimiter=',', usecols=(0, 2, 3), converters=dict(zip((0, 2, 3), (float, float, float))), dtype=([('i1', '<i4'), ('i2', '<f4'), ('i3', '<i4')]))
array([(1, 3.2000000476837158, 4), (1, 3.2000000476837158, 4),
(1, 3.2000000476837158, 4), (1, 3.2000000476837158, 4),
(1, 3.2000000476837158, 4), (1, 3.2000000476837158, 4),
(1, 3.2000000476837158, 4), (1, 3.2000000476837158, 4),
(1, 3.2000000476837158, 4)],
dtype=[('i1', '<i4'), ('f1', '<f4'), ('i2', '<i4')])
当然,在这种情况下,您实际上并不需要converters
- 这实际上是将'True'
之类的任意字符串值转换为数值。此外,如果您确实需要一个简单的二维数组而不是一个记录数组,那么不要传递记录格式:
>>> numpy.loadtxt('th.txt', delimiter=',', usecols=(0, 2, 3), dtype=int)
array([[1, 3, 4],
[1, 3, 4],
[1, 3, 4],
[1, 3, 4],
[1, 3, 4],
[1, 3, 4],
[1, 3, 4],
[1, 3, 4],
[1, 3, 4]])
但是如果你这样做,你不能按列指定格式。
答案 1 :(得分:3)
要指定不同列的类型,可以使用参数dtype
代替converters
:
dtype=(int,float,float,int,int)
编辑:
显然,这种dtype
规范似乎不适用于loadtxt
,但它适用于genfromtxt
(是否有人知道为什么这不起作用{ {1}},或者这是loadtxt
)
如果您想使用genfromtxt
,带有元组的结构化dtype规范可以正常工作,例如loadtxt
而不是[('f0', int), ('f1', float)]
但还有另一个问题。使用这样的结构化dtypes和结构化数组(不同列的不同类型)时,(int, float)
似乎不起作用。至少我试过一个简单的例子。但这可能是一个已经解决的错误:http://projects.scipy.org/numpy/ticket/1458(但为此,你必须升级到1.6)。