假设我有以下 numpy 结构化数组:
>>> a = numpy.array((1, 2.0, 'buckle_my_shoe'),dtype=('i4,f8,a14'))
array((1, 2.0, 'buckle_my_shoe'),
dtype=[('f0', '<i4'), ('f1', '<f8'), ('f2', 'S14')])
我想将它保存到文本文件中的单个空格或制表符分隔行。如果数组都是同一类型,我可以使用 numpy.savetxt('myfile.dat,myarray,newline="")。然而,这似乎不喜欢混合数据类型/结构化数组,例如:
file('myfile.dat', 'a')
numpy.savetxt('myfile.dat',a,newline=" ")
给出这个错误:
IndexError: tuple index out of range
有人可以推荐一种方法吗?
请您参考如下方法:
编辑:无论出于何种原因,我似乎都无法单独留下这个答案,所以这里有一个更简洁的版本,它不会不必要地使用 csv 模块.作为记录,@askewchan 的回答仍然更好!
a = numpy.array([(1, 2.0, 'buckle_my_shoe'),
(3,4.0,'lock_the_door')],dtype=('i4,f8,a14'))
with open('test.txt','w') as f:
f.write(' '.join([str(item) for sublist in a for item in sublist]))
print open('test.txt','r').read()
输出:
1 2.0 buckle_my_shoe 3 4.0 lock_the_door
