回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我正在尝试使用带converters参数的numpy.loadtxt从文本文件读取数据。我有int和string的混合列。代码是:</p>
<pre><code>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))))
</code></pre>
<p>数据被正确地读入和解包,但所有变量(a、b、c、d和e)最终都是浮点数。我在转换器语法上犯了错误吗?</p>
<p><strong>编辑尝试回答</strong></p>
<p>我试着按照@joris的建议使用dtype=(int,float,float,int,int):</p>
<pre><code>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))
</code></pre>
<p>但我得到了以下错误:</p>
<pre><code> 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>
</code></pre>
<p>我用的是NumPy v.1.5.1。</p>