user3737702
user3737702

Reputation: 641

Saving 1D numpy arrays of different sizes to txt file columnwise

Below is the illustration code

from pylab import *

 a = array([1,2,3])
 b = array([4,5])

What I want test.out has is

1 4
2 5
3

previously, people has given solution of store of 1D numpy arrays of different sizes to txt file rowwise: Saving numpy array to txt file row wise

Then how to save them columnwise?

Of course you can use three array like this

 a = array([1,4])
 b = array([2,5])
 c=array([3])

and save them in row wise however it is not a smart way, when there is a lot of 1D arrays.

Upvotes: 0

Views: 1938

Answers (2)

hpaulj
hpaulj

Reputation: 231375

My answer in https://stackoverflow.com/a/34242952/901925 could be adapted to this case

3 arrays of different length; could be lists

In [715]: heights=np.array([40,50])
In [716]: widths=np.array([60,65,70])
In [717]: yrs=np.array([1995,1996,1997,1998])

use itertools.zip_longest to iterate through them, with a fillvalue where values are missing:

In [718]: for xyz in itertools.zip_longest(yrs,widths,heights,fillvalue=''):
    print('%-12s,%-12s,%-12s'%xyz)
   .....:     
1995        ,60          ,40          
1996        ,65          ,50          
1997        ,70          ,            
1998        ,            ,  

to write to a file use:

In [719]: with open('temp.txt','w') as f:
    for xyz in itertools.zip_longest(yrs,widths,heights,fillvalue=''):
        f.write('%-12s,%-12s,%-12s\n'%xyz)
   .....:         
In [720]: cat temp.txt
1995        ,60          ,40          
1996        ,65          ,50          
1997        ,70          ,            
1998        ,            ,  

(itertools.zip_longest in PY3, izip_longest in Py2).

Upvotes: 2

Colonel Beauvel
Colonel Beauvel

Reputation: 31161

A simple approach with pandas:

import pandas as pd

d  = dict(a=a, b=b)
df = pd.DataFrame.from_dict(d, orient='index').transpose().fillna('')

#   a  b
#0  1  4
#1  2  5
#2  3   

And write in a csv (you do not want to write the index nor the column):

df.to_csv('file.csv', index=False, header=False)

Upvotes: 2

Related Questions