Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving arrays as columns with np.savetxt

Tags:

python

numpy

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 
like image 643
Stripers247 Avatar asked Mar 04 '13 00:03

Stripers247


People also ask

How do I save an array to an NP file?

You can save your NumPy arrays to CSV files using the savetxt() function. This function takes a filename and array as arguments and saves the array into CSV format. You must also specify the delimiter; this is the character used to separate each variable in the file, most commonly a comma.

How do I save a NumPy 2D array?

savetxt() is a method in python in numpy library to save an 1D and 2D array to a file. numpy. loadtxt() is a method in python in numpy library to load data from a text file for faster reading.

What is Savetxt in Python?

savetxt() function in NumPy array Python. In Python, this method is available in the NumPy package module and it saves array numbers in text file format. In this example, we have used the header, delimiter parameter in numpy.

What is FMT in Savetxt?

fmtstr or sequence of strs, optional. A single format (%10.5f), a sequence of formats, or a multi-format string, e.g. 'Iteration %d – %10.5f', in which case delimiter is ignored. For complex X, the legal options for fmt are: a single specifier, fmt='%. 4e', resulting in numbers formatted like ' (%s+%sj)' % (fmt, fmt)


2 Answers

Use numpy.c_[]:

np.savetxt('myfile.txt', np.c_[x,y,z]) 
like image 135
HYRY Avatar answered Oct 08 '22 07:10

HYRY


Use numpy.transpose():

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

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

like image 32
Hamid Avatar answered Oct 08 '22 07:10

Hamid