Saving arrays as columns with np.savetxt

PythonNumpy

Python Problem Overview


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

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

Python Solutions


Solution 1 - Python

Use numpy.c_[]:

np.savetxt('myfile.txt', np.c_[x,y,z])

Solution 2 - Python

Use numpy.transpose():

np.savetxt('myfile.txt', np.transpose([x,y,z]))

I find this more intuitive than using np.c_[].

Solution 3 - Python

I find numpy.column_stack() most intuitive:

np.savetxt('myfile.txt', np.column_stack([x,y,z]))

Solution 4 - Python

Use zip:

np.savetxt('myfile2.txt', zip(x,y,z), fmt='%.18g')

For python3 list+zip:

np.savetxt('myfile.txt', list(zip(x,y,z)), fmt='%.18g')

To understand the workaround see here: https://stackoverflow.com/questions/26090117/how-can-i-get-the-old-zip-in-python3 and https://github.com/numpy/numpy/issues/5951.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionStripers247View Question on Stackoverflow
Solution 1 - PythonHYRYView Answer on Stackoverflow
Solution 2 - PythonHamidView Answer on Stackoverflow
Solution 3 - PythonjanView Answer on Stackoverflow
Solution 4 - PythonFriedrichView Answer on Stackoverflow