python - saving vector-array data with different lengths at columns of a txt file

39 Views Asked by At

I have two sets of data as

A=[array([1,2,3]),array([1,2,3,4]), ... array([11,13,2,1,5,7,9,0])]
B=[array([11,21,31]),array([16,27,38,48]), ... array([114,134,24,14,54,74,94,04])]

I want to save the arrays as consecutive x-y columns in a txt file such as: enter image description here in which the columns of A and B data are consequantly written.

However, because of different lenghts, I can not apply the command: np.savetxt(np.transpose(A). Any help is appreciated.

I tried using np.savetxt(np.transpose) but here the columns have different lengths and this command fails.

1

There are 1 best solutions below

4
mozway On

You could use + tabulate to generate the desired format with flexibility:

import numpy as np
import pandas as pd
from tabulate import tabulate

A = [np.array([1,2,3]),
     np.array([1,2,3,4]),
     np.array([11,13,2,1,5,7,9,0])]
B = [np.array([11,21,31]),
     np.array([16,27,38,48]),
     np.array([114,134,24,14,54,74,94,4])]

tmp = (pd
   .concat(map(pd.DataFrame, [A, B]))
   .sort_index(kind='stable').T
   .convert_dtypes().astype(object).fillna('')
)

with open('out.txt', 'w') as f:
    f.write(tabulate(tmp, showindex=False, numalign='left', tablefmt='plain'))

Output:

1  11  1  16  11  114
2  21  2  27  13  134
3  31  3  38  2   24
       4  48  1   14
              5   54
              7   74
              9   94
              0   4