python - 将不同长度的向量数组数据保存到txt文件的列中

1 投票
1 回答
34 浏览
提问于 2025-04-14 17:35

我有两组数据,如下所示:

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])]

我想把这些数组保存为一个文本文件,格式是连续的x-y列,像这样:

enter image description here

在这个文件中,A和B的数据列是依次写在一起的。

但是,由于它们的长度不同,我不能使用这个命令:

np.savetxt(np.transpose(A)
希望能得到一些帮助。

我尝试使用 np.savetxt(np.transpose),但因为列的长度不同,这个命令失败了。

1 个回答

0

你可以使用 tabulate 来灵活地生成你想要的格式:

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'))

输出结果:

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

撰写回答