使用numpy.savetxt时的值错误
我想把每个numpy数组(A、B和C)保存为文本文件中的一列,列与列之间用空格分隔:
import numpy as np
A = np.array([5,7,8912,44])
B = np.array([5.7,7.45,8912.43,44.99])
C = np.array([15.7,17.45,18912.143,144.99])
np.savetxt('test.txt', (A, B, C), fmt='%s %s %s')
但是我遇到了以下错误:
ValueError: fmt的格式数量不对: %s %s %s
该怎么解决呢?
1 个回答
10
np.savetxt('/tmp/test.txt', np.column_stack((A, B, C)), fmt='%s %s %s')
结果是
5.0 5.7 15.7
7.0 7.45 17.45
8912.0 8912.43 18912.143
44.0 44.99 144.99
注意,使用 fmt='%s'
也会得到相同的结果。
如果你尝试
np.savetxt('/tmp/test.txt', (A, B, C))
你会发现 NumPy 会把每个一维数组写在不同的行上,也就是横着写。由于每行使用的格式是 fmt='%s %s %s'
,而每行有4个值,所以就出现了错误。
我们可以通过传递一个二维数组 np.column_stack((A, B, C))
给 np.savetxt
来解决这个问题。