我正在尝试使用带有 converters 参数的 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)最终都变成了 float 。我在转换器语法中犯了错误吗?
编辑尝试回答
我尝试按照@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=(int,float,float,int,int)
编辑:
显然,这种类型的 dtype
规范似乎不适用于 loadtxt
,但它适用于 genfromtxt
(有没有人知道为什么这不适用于 loadtxt
,或者这是 genfromtxt
的额外功能之一?)
如果你想使用loadtxt
,一个带有元组的结构化数据类型规范可以工作,比如[('f0', int), ('f1', float)]
而不是 (int, float)
但是还有一个问题。使用此类结构化数据类型和结构化数组(不同列的不同类型)时,unpack
似乎不起作用。至少我试过一个简单的例子。但这可能是一个已经解决的错误:http://projects.scipy.org/numpy/ticket/1458 (但为此,您甚至必须升级到 1.6)。
关于python - 不理解 NumPy loadtxt 中的转换器行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6416688/