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
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.
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.
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.
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)
Use numpy.c_[]
:
np.savetxt('myfile.txt', np.c_[x,y,z])
Use numpy.transpose()
:
np.savetxt('myfile.txt', np.transpose([x,y,z]))
I find this more intuitive than using np.c_[]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With