按行将numpy数组保存到txt文件 [英] Saving numpy array to txt file row wise

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

问题描述

我有一个表格形式的numpy数组

I have an numpy array of form

a = [1,2,3]

我要将其保存为.txt文件,以使该文件看起来像这样:

which I want to save to a .txt file such that the file looks like:

1 2 3

如果我使用numpy.savetxt,则得到的文件如下:

If I use numpy.savetxt then I get a file like:

1
2
3

我想对此应该有一个简单的解决方案,有什么建议吗?

There should be a easy solution to this I suppose, any suggestions?

推荐答案

如果为numpy >= 1.5,则可以执行以下操作:

If numpy >= 1.5, you can do:

#请注意,文件名用双引号引起来,
#示例"filename.txt"

# note that the filename is enclosed with double quotes,
# example "filename.txt"

numpy.savetxt("filename", a, newline=" ")

修改

相同长度的几个一维数组

several 1D arrays with same length

a = numpy.array([1,2,3])
b = numpy.array([4,5,6])
numpy.savetxt(filename, (a,b), fmt="%d")

# gives:
# 1 2 3
# 4 5 6

多个长度可变的一维数组

several 1D arrays with variable length

a = numpy.array([1,2,3])
b = numpy.array([4,5])

with open(filename,"w") as f:
    f.write("\n".join(" ".join(map(str, x)) for x in (a,b)))

# gives:
# 1 2 3
# 4 5

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

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