Savetxt two columns in python, numpy

I have some data as a list of numpy two-dimensional arrays

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 can I do this using numpy savetxt

+6
source share
1 answer
 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']) 

gives

 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 horizontal stacks of arrays. Since R and phase are both two-dimensional, np.hstack([R, phase]) gives

 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 the desired result.

+5
source

Source: https://habr.com/ru/post/944037/


All Articles