np.savetxt写入csv文件。在这种情况下,诀窍是将两个数组/列表组合成一个复合数组,然后根据需要对其进行格式化:In [100]: mydata = np.arange(1,16).reshape(3,5)
In [101]: mydata
Out[101]:
array([[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10],
[11, 12, 13, 14, 15]])
In [102]: mydata = np.arange(1,16).reshape(3,5).T
In [103]: mydata
Out[103]:
array([[ 1, 6, 11],
[ 2, 7, 12],
[ 3, 8, 13],
[ 4, 9, 14],
[ 5, 10, 15]])
In [104]: elements = np.arange(18,31,3)
In [105]: elements
Out[105]: array([18, 21, 24, 27, 30])
In [106]: arr = np.column_stack((elements, mydata))
In [107]: arr
Out[107]:
array([[18, 1, 6, 11],
[21, 2, 7, 12],
[24, 3, 8, 13],
[27, 4, 9, 14],
[30, 5, 10, 15]])
In [108]: np.savetxt('test.txt',arr, fmt='%2d %3d %3d %3d')
In [109]: cat test.txt
18 1 6 11
21 2 7 12
24 3 8 13
27 4 9 14
30 5 10 15
相当于我可以将zip组合成两个数组;将row值组合成一个元组,并格式化为:In [112]: for e, d in zip(elements, mydata):
...: ed = (e,)+tuple(d)
...: print('%2d %3d %3d %3d'%ed)
# print(('%d '%e) + ' '.join(['%3d']*3)%tuple(d))
...:
18 1 6 11
21 2 7 12
24 3 8 13
27 4 9 14
30 5 10 15
我正在使用print,但您可以将其切换为文件写入。