我对包裹有个奇怪的问题。我用它来读取一个包含许多列(可用numpy.genfromtxt)的数据文件,但即使将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]

我在这里做错什么了?

最佳答案

这就是你想要的吗?

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
编辑:
我对以下数据进行了测试:
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
#-------^--------

如果d=np.genfromtxt('a.x', dtype=None, unpack=True),解包确实失败:
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)

使用dtype=Nonedefault dtype时,解包工作:
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']

09-10 17:01