<p>如果使用<a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html" rel="noreferrer">np.genfromtxt</a>,则可以指定<code>dtype=None</code>,这将告诉<code>genfromtxt</code>智能地猜测每个列的数据类型。最方便的是,它免除了指定string列所需字节数的麻烦。(通过指定例如<code>np.str</code>来省略字节数不起作用。)</p>
<pre><code>In [58]: np.genfromtxt('data.txt', delimiter=',', dtype=None, names=('sepal length', 'sepal width', 'petal length', 'petal width', 'label'))
Out[58]:
array([(5.1, 3.5, 1.4, 0.2, 'Iris-setosa'),
(4.9, 3.0, 1.4, 0.2, 'Iris-setosa'),
(5.8, 2.7, 4.1, 1.0, 'Iris-versicolor'),
(6.2, 2.2, 4.5, 1.5, 'Iris-versicolor'),
(6.4, 3.1, 5.5, 1.8, 'Iris-virginica'),
(6.0, 3.0, 4.8, 1.8, 'Iris-virginica')],
dtype=[('sepal_length', '<f8'), ('sepal_width', '<f8'), ('petal_length', '<f8'), ('petal_width', '<f8'), ('label', 'S15')])
</code></pre>
<hr/>
<p>如果您确实想使用<code>np.loadtxt</code>,那么要以最小的更改修复代码,您可以使用:</p>
<pre><code>np.loadtxt("data.txt",
dtype={'names': ('sepal length', 'sepal width', 'petal length', 'petal width', 'label'),
'formats': (np.float, np.float, np.float, np.float, '|S15')},
delimiter=',', skiprows=0)
</code></pre>
<p>主要的区别只是将<code>np.str</code>更改为<code>|S15</code>(15字节的字符串)。</p>
<p>还要注意
<code>open("data.txt"), 'r'</code>应该是<code>open("data.txt", 'r')</code>。但是由于<code>np.loadtxt</code>可以接受文件名,因此根本不需要使用<code>open</code>。</p>