numpy loadtxt为单行文件返回0-d数组,烦人吗?

时间:2014-02-25 17:47:07

标签: python arrays python-3.x numpy

我有问题,我编写了使用以下numpy调用的代码

columnNames = ['A','B','C'];
dt = [(s,np.float64) for s in columnNames];

# load structured unit        
SimData = np.loadtxt( file ,dtype=dt, delimiter="\t", comments='#')

如果我的文件只包含一行,那么SimData['A'][0]不存在,因为该命令返回一个0-d数组,这有点烦人吗? 如何使用也适用于单行文件的索引编写代码?

1 个答案:

答案 0 :(得分:2)

您可以使用参数ndmin=1强制loadtxt返回至少为一维的结果:

In [10]: !cat data.tsv
100 200 300

In [11]: a = np.loadtxt('data.tsv', dtype=dt, delimiter='\t', ndmin=1)

In [12]: a.shape
Out[12]: (1,)

In [13]: a
Out[13]: 
array([(100.0, 200.0, 300.0)], 
      dtype=[('A', '<f8'), ('B', '<f8'), ('C', '<f8')])