<p>定义简单文本:</p>
<pre><code>In [55]: txt= '''foo,bar,test
...: a,1,2
...: b,3,4
...: '''
</code></pre>
<p>加载<code>genfromtxt</code>:</p>
<pre><code>In [60]: data = np.genfromtxt(txt.splitlines(), encoding=None, names=True, dtype=None, delimiter=',')
In [61]: data
Out[61]:
array([('a', 1, 2), ('b', 3, 4)],
dtype=[('foo', '<U1'), ('bar', '<i8'), ('test', '<i8')])
</code></pre>
<p>请注意具有不同数据类型和名称的数据类型字段。你知道吗</p>
<p>按名称访问字段:</p>
<pre><code>In [64]: data['foo']
Out[64]: array(['a', 'b'], dtype='<U1')
</code></pre>
<p>按索引修改一个字段:</p>
<pre><code>In [65]: data['bar']
Out[65]: array([1, 3])
In [66]: data['bar'][0] = 23
</code></pre>
<p>用布尔测试(或<code>where</code>)修改另一个:</p>
<pre><code>In [67]: test = data['test']
In [68]: test
Out[68]: array([2, 4])
In [69]: test==2
Out[69]: array([ True, False])
In [70]: test[test==2]=0
In [71]: test
Out[71]: array([0, 4])
In [72]: data
Out[72]:
array([('a', 23, 0), ('b', 3, 4)],
dtype=[('foo', '<U1'), ('bar', '<i8'), ('test', '<i8')])
</code></pre>
<p>如果将数字字段分组为一个字段,则替换可能更容易(但这需要更多地了解结构化数组数据类型):</p>
<pre><code>In [80]: data = np.genfromtxt(txt.splitlines(), encoding=None, skip_header=1, dtype=[('id','U3'),('foo',int,2)],
...: delimiter=',')
In [81]: data
Out[81]:
array([('a', [1, 2]), ('b', [3, 4])],
dtype=[('id', '<U3'), ('foo', '<i8', (2,))])
In [82]: data['foo']
Out[82]:
array([[1, 2],
[3, 4]])
</code></pre>