numpy.genfromtxt未解包

时间:2014-02-21 15:07:26

标签: python file-io numpy

我对包numpy.genfromtxt有一个奇怪的问题。我用它来读取包含多个列的数据文件(可用here),但即使unpack设置为True,这些也不会被解压缩。

这是MWE

import numpy as np
f_data = np.genfromtxt('file.dat', dtype=None, unpack=True)

print f_data[3]
(237, 304.172, 2017.48, 15.982, 0.005, 0.889, 0.006, -2.567, 0.004, 1.205, 0.006)

(我使用dtype=None因为文件可以散布在各处)

如您所见,它返回一行而不是一个解压缩的列。

如果我使用np.loadtxt,它会按预期工作:

f_data = np.loadtxt('file.dat', unpack=True)

print f_data[3]
[ 16.335  16.311  15.674  15.982  16.439  15.903  15.313  18.35   15.643  14.081  16.578  11.477]

我在这里做错了什么?

2 个答案:

答案 0 :(得分:2)

这是你想要的吗?

In [448]: i=3
     ...: d=np.genfromtxt(fname, None) #d is a recorded array (or structured array)
     ...: d['f%d'%i] #Addressing Array Columns by Name
Out[448]: array([ 16.335,  16.311,  15.674,  15.982,  16.439,  15.903])

见:

http://wiki.scipy.org/Cookbook/Recarray

http://docs.scipy.org/doc/numpy/user/basics.rec.html#module-numpy.doc.structured_arrays

编辑:

我在以下数据上测试了d=np.genfromtxt('a.x', dtype=None, unpack=True)

144     a578.06 873.72  16.335  0.003 
#-------^--------
180     593.41  665.748 16.311  0.003 
147     868.769 908.472 15.674  0.003
237     asdf.172 2017.48 15.982  0.005
#-------^--------

dtype=None,unpack确实失败了:

In [538]: d=np.genfromtxt('a.x', dtype=None, unpack=True)
     ...: print d[3]
     ...: print d[1]
(237, 'asdf.172', 2017.48, 15.982, 0.005)
(180, '593.41', 665.748, 16.311, 0.003)

在使用default dtypedtype=str时,解包有效:

In [539]: d=np.genfromtxt('a.x',  unpack=True)
     ...: print d[3]
     ...: print d[1]
[ 16.335  16.311  15.674  15.982  16.439  15.903]
[      nan   593.41    868.769       nan  1039.71    385.864]

In [540]: d=np.genfromtxt('a.x', dtype=str, unpack=True)
     ...: print d[3]
     ...: print d[1]
['16.335' '16.311' '15.674' '15.982' '16.439' '15.903']
['a578.06' '593.41' '868.769' 'asdf.172' '1039.71' '385.864']

答案 1 :(得分:0)

更改

dtype=None

dtype=str

并删除解包,因为这将转置数据。并且为了良好的实践添加分隔符:)

相关问题