I have some data as numpy 2D array list-
array([[ 0.62367947],
[ 0.95427859],
[ 0.97984112],
[ 0.7025228 ],
[ 0.86436385],
[ 0.71010739],
[ 0.98748138],
[ 0.75198057]])
array([[-1., 1., -1.],
[-1., 1., 1.],
[ 1., 1., 1.],
[ 1., -1., 1.],
[-1., -1., -1.],
[ 1., 1., -1.],
[ 1., -1., -1.],
[-1., -1., 1.]])
And I want to save them in a txt file so that they look like
0.62367947 -1 1 -1
0.95427859 -1 1 1
0.97984112 1 1 1
Can someone help me how I can do it using numpy savetxt
column_stack() in Python. numpy. column_stack() function is used to stack 1-D arrays as columns into a 2-D array.It takes a sequence of 1-D arrays and stack them as columns to make a single 2-D array. 2-D arrays are stacked as-is, just like with hstack function.
The savetxt() function is used to save an array to a text file. Syntax: numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='#', encoding=None) Version: 1.15.0.
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.
numpy. c_ = <numpy.lib.index_tricks.CClass object> Translates slice objects to concatenation along the second axis. This is short-hand for np. r_['-1,2,0', index expression] , which is useful because of its common occurrence.
import numpy as np
R = np.array([[0.62367947],
[0.95427859],
[0.97984112],
[0.7025228],
[0.86436385],
[0.71010739],
[0.98748138],
[0.75198057]])
phase = np.array([[-1., 1., -1.],
[-1., 1., 1.],
[1., 1., 1.],
[1., -1., 1.],
[-1., -1., -1.],
[1., 1., -1.],
[1., -1., -1.],
[-1., -1., 1.]])
np.savetxt('R2.txt', np.hstack([R, phase]), fmt=['%0.8f','%g','%g','%g'])
yields
0.62367947 -1 1 -1
0.95427859 -1 1 1
0.97984112 1 1 1
0.70252280 1 -1 1
0.86436385 -1 -1 -1
0.71010739 1 1 -1
0.98748138 1 -1 -1
0.75198057 -1 -1 1
np.hstack stacks arrays horizontally. Since R
and phase
are both 2-dimensional, np.hstack([R, phase])
yields
In [137]: np.hstack([R,phase])
Out[137]:
array([[ 0.62367947, -1. , 1. , -1. ],
[ 0.95427859, -1. , 1. , 1. ],
[ 0.97984112, 1. , 1. , 1. ],
[ 0.7025228 , 1. , -1. , 1. ],
[ 0.86436385, -1. , -1. , -1. ],
[ 0.71010739, 1. , 1. , -1. ],
[ 0.98748138, 1. , -1. , -1. ],
[ 0.75198057, -1. , -1. , 1. ]])
Passing this 2D array to np.savetxt
gives you the desired result.
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