Gab*_*iel 5 python file-io numpy
我对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.structed_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,解压确实失败:
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 dtype或时dtype=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']
| 归档时间: | 
 | 
| 查看次数: | 2131 次 | 
| 最近记录: |