我正在尝试使用带converters参数的numpy.loadtxt从文本文件读取数据。我有int和string的混合列。代码是:
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。
要指定不同列的类型,可以使用参数
dtype
,而不是converters
:编辑:
显然,这种类型的
dtype
规范似乎不适用于loadtxt
,但它适用于genfromtxt
(有人知道为什么这不适用于loadtxt
,或者这是genfromtxt
的额外功能之一吗?)如果您想使用
loadtxt
,一个带元组的结构化dtype规范可以工作,比如[('f0', int), ('f1', float)]
,而不是(int, float)
但还有一个问题。当使用这样的结构化数据类型和这样的结构化数组(针对不同列的不同类型)时,
unpack
似乎不起作用。至少举个简单的例子。但这可能是一个已经解决的错误:http://projects.scipy.org/numpy/ticket/1458(但要做到这一点,您必须升级到甚至1.6)。loadtxt
文档表明converters
应该包含以下函数specifically return floats:如果您需要整数,则需要使用
dtype
关键字来转换浮点数。当然,在这种情况下实际上不需要
converters
——这实际上是为了将'True'
这样的任意字符串值转换为数值。此外,如果您实际上需要一个简单的二维数组而不是记录数组,则不要传递记录格式:但如果这样做,就不能按列指定格式。
相关问题 更多 >
编程相关推荐