Search code examples
pythonarraysnumpyvertical-text

numpy vertical array write to text file


I have two 5 by 1 vertical array

x = [[1]
     [2]
     [3]
     [4]
     [5]]
y = [[92]
     [93]
     [94]
     [95]
     [96]]

I need to output(belo) in a text file

1 92
2 93
3 94
4 95
5 96

My script looks like this

x= numpy.vstack((z))
y= numpy.vstack((r))
numpy.savetxt('fin_lower.dat', ??, fmt='%.4e')

any help is appreciated


Solution

  • Make the 2 arrays:

    In [117]: x=np.arange(1,6).reshape(-1,1) 
    In [119]: y=np.arange(92,97).reshape(-1,1)
    

    since they are 2d, concatenate works nicely; hstack and column_stack.

    In [122]: xy=np.concatenate((x,y),axis=1)
    
    In [123]: xy
    Out[123]: 
    array([[ 1, 92],
           [ 2, 93],
           [ 3, 94],
           [ 4, 95],
           [ 5, 96]])
    
    In [124]: xy=np.hstack((x,y))
    

    Now I have a 2d array (5 rows, 2 col) that can be saved in the desired format:

    In [126]: np.savetxt('test.txt',xy)
    In [127]: cat test.txt
    1.000000000000000000e+00 9.200000000000000000e+01
    2.000000000000000000e+00 9.300000000000000000e+01
    3.000000000000000000e+00 9.400000000000000000e+01
    4.000000000000000000e+00 9.500000000000000000e+01
    5.000000000000000000e+00 9.600000000000000000e+01
    
    In [128]: np.savetxt('test.txt',xy, fmt='%.4e')
    In [129]: cat test.txt
    1.0000e+00 9.2000e+01
    2.0000e+00 9.3000e+01
    3.0000e+00 9.4000e+01
    4.0000e+00 9.5000e+01
    5.0000e+00 9.6000e+01
    
    In [131]: np.savetxt('test.txt',xy, fmt='%d')    
    In [132]: cat test.txt
    1 92
    2 93
    3 94
    4 95
    5 96