Python 使用 np.savetxt 将数组保存为列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15192847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Saving arrays as columns with np.savetxt
提问by Stripers247
I am trying to do something that is probable very simple. I would like to save three arrays to a file as columns using 'np.savetxt' When I try this
我正在尝试做一些可能非常简单的事情。我想使用“np.savetxt”将三个数组作为列保存到一个文件中
x = [1,2,3,4]
y = [5,6,7,8]
z = [9,10,11,12]
np.savetxt('myfile.txt', (x,y,z), fmt='%.18g', delimiter=' ', newline=os.linesep)
The arrays are saved like this
数组是这样保存的
1 2 3 4
5 6 7 8
9 10 11 12
But what I wold like is this
但我喜欢的是这个
1 5 9
2 6 10
3 7 11
4 8 12
采纳答案by HYRY
回答by Hamid
Use numpy.transpose():
使用numpy.transpose():
np.savetxt('myfile.txt', np.transpose([x,y,z]))
I find this more intuitive than using np.c_[].
我发现这比使用np.c_[].
回答by Friedrich
Use zip:
使用邮编:
np.savetxt('myfile2.txt', zip(x,y,z), fmt='%.18g')
np.savetxt('myfile2.txt', zip(x,y,z), fmt='%.18g')
For python3 list+zip:
对于python3列表+zip:
np.savetxt('myfile.txt', list(zip(x,y,z)), fmt='%.18g')
np.savetxt('myfile.txt', list(zip(x,y,z)), fmt='%.18g')
To understand the workaround see here: How can I get the "old" zip() in Python3?and https://github.com/numpy/numpy/issues/5951.
要了解解决方法,请参见此处:How can I get the "old" zip() in Python3? 和https://github.com/numpy/numpy/issues/5951。
回答by jan
I find numpy.column_stack()most intuitive:
我觉得numpy.column_stack()最直观:
np.savetxt('myfile.txt', np.column_stack([x,y,z]))

