genfromtxt不同的数据类型

时间:2017-07-31 09:58:03

标签: python numpy import genfromtxt

我正在尝试从包含不同列数的文本文件中导入数据。我知道第一列将始终是一个int,后续的cols将在所有文件中浮动。如何使用dtypes明确指定?

dtypes=[int,float,float,float...] #this number will change depending on the number of columns in the file

data=np.genfromtxt(file,dtype=dtypes,delimiter='\t',skip_header=11) #read in 
the data

由于

1 个答案:

答案 0 :(得分:0)

您可以先将所有内容读作floats,然后在知道有多少列后将数组转换为structured array

##input.txt:
##    1 1.4 5e23
##    2 2.3 5e-12
##    3 5.7 -1.3e-2

import numpy as np

data = np.genfromtxt('input.txt')
print(data)
print('-'*50)

colw = data.shape[1]

dtypes = [('col0', int)]+[('col{}'.format(i+1),float) for i in range(colw-1)]
print(dtypes)
print('-'*50)

converted_data = np.array([tuple(r) for r in data], dtype = dtypes)

print(converted_data)

这给出了以下输出:

[[  1.00000000e+00   1.40000000e+00   5.00000000e+23]
 [  2.00000000e+00   2.30000000e+00   5.00000000e-12]
 [  3.00000000e+00   5.70000000e+00  -1.30000000e-02]]
--------------------------------------------------
[('col0', <class 'int'>), ('col1', <class 'float'>), ('col2', <class 'float'>)]
--------------------------------------------------
[(1,  1.4,   5.00000000e+23) (2,  2.3,   5.00000000e-12)
 (3,  5.7,  -1.30000000e-02)]

在Python 3.5上测试