你可以先阅读一切,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.0测试版
你能发表你输入文件的头几行和你收到的错误信息吗? –
'dtype = None'会为你工作吗?或者将dtype保留为默认浮点数并获得一个2d数组而不是结构化数组。 – hpaulj
我想要一个二维数组作为后来我想切片的数据和改变某些列。我可以将它保留为浮点数,但是我正在编写新文件,并希望尽可能地减小文件大小,只要可能,将数字减少到int。 –