numpy将不同类型的数组保存到文本文件中 [英] numpy save an array of different types to a text file

查看:1512
本文介绍了numpy将不同类型的数组保存到文本文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下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 =)。但是,这似乎不像混合数据类型/结构化数组,例如:

pre $ file $('myfile.dat',' a')
numpy.savetxt('myfile.dat',a,newline =)



  IndexError:元组索引超出范围

任何人都可以推荐一个这样做的方法吗?

解决方案

编辑:出于任何原因,我似乎无法单独离开这个答案,所以这里是一个更清洁的版本,不使用 csv

  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 for item in sublist]))
print open('test.txt','r')。read()

输出:

  1 2.0 buckle_my_shoe 3 4.0 lock_the_door 


Say I have the following numpy structured array:

>>> 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')])

and I want to save it to a single space or tab delimited row in a text file. If the array were all of the same type I could use numpy.savetxt('myfile.dat,myarray,newline=" "). However, this seems to not like mixed data types/structured arrays, for example:

file('myfile.dat', 'a')
numpy.savetxt('myfile.dat',a,newline=" ")

gives this error:

IndexError: tuple index out of range

Can anyone recommend a way of doing this?

解决方案

Edit: For whatever reason I can't seem to be able to leave this answer alone, so here's a cleaner version that doesn't use the csv module unnecessarily. For the record, @askewchan's answer is still better!

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()

Output:

1 2.0 buckle_my_shoe 3 4.0 lock_the_door

这篇关于numpy将不同类型的数组保存到文本文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆