用 numpy savetxt 保存.数组元素作为列



我对Python很陌生,并试图戒掉我对Matlab的依赖。我正在将实验室的许多机器视觉代码转换为Python,但我只是停留在保存的一个方面。在代码的每一行中,我们将 6 个变量保存在一个数组中。我希望这些作为 6 列之一输入到 txt 与 bumpy.savetxt 的 txt 文件中。然后,跟踪循环的每次迭代都会为该给定帧添加类似的变量,作为 txt 文件中的下一行。

但是我一直得到一个随每个循环而增长的单个列。我附上了一个简单的代码来显示我的问题。当它循环时,将生成一个称为输出的变量。我希望这是 txt 文件的三列,循环的每次迭代都是一个新行。有什么简单的方法可以做到这一点吗?

import numpy as np
dataFile_Path = "dataFile.txt"
dataFile_id = open(dataFile_Path, 'w+')
for x in range(0, 9):
variable = np.array([2,3,4])
output = x*variable+1
output.astype(float)
print(output)
np.savetxt(dataFile_id, output, fmt="%d")
dataFile_id.close()
In [160]: for x in range(0, 9):
...:     variable = np.array([2,3,4])
...:     output = x*variable+1
...:     output.astype(float)
...:     print(output)
...:     
[1 1 1]
[3 4 5]
[5 7 9]
[ 7 10 13]
[ 9 13 17]
[11 16 21]
[13 19 25]
[15 22 29]
[17 25 33]

所以你一次写一行。savetxt通常用于编写 2D 数组。

请注意,打印仍然是整数 -astype返回一个新数组,它不会就地更改内容。

但是因为你给它一个数组,所以它把它们写成列:

In [177]: f = open('txt','bw+')
In [178]: for x in range(0, 9):
...:     variable = np.array([2,3,4])
...:     output = x*variable+1
...:     np.savetxt(f, output, fmt='%d')
...:     
In [179]: f.close()
In [180]: cat txt
1
1
1
3
4
5
5
7
9

相反,如果我给savetxt一个 2d 数组((1,3( 形状(,它会写

In [181]: f = open('txt','bw+')
In [182]: for x in range(0, 9):
...:     variable = np.array([2,3,4])
...:     output = x*variable+1
...:     np.savetxt(f, [output], fmt='%d')
...:     
...:     
In [183]: f.close()
In [184]: cat txt
1 1 1
3 4 5
5 7 9
7 10 13
9 13 17
11 16 21
13 19 25
15 22 29
17 25 33

但更好的方法是构造 2d 数组,并通过一个savetxt调用来编写它:

In [185]: output = np.array([2,3,4])*np.arange(9)[:,None]+1
In [186]: output
Out[186]: 
array([[ 1,  1,  1],
[ 3,  4,  5],
[ 5,  7,  9],
[ 7, 10, 13],
[ 9, 13, 17],
[11, 16, 21],
[13, 19, 25],
[15, 22, 29],
[17, 25, 33]])
In [187]: np.savetxt('txt', output, fmt='%10d')
In [188]: cat txt
1          1          1
3          4          5
5          7          9
7         10         13
9         13         17
11         16         21
13         19         25
15         22         29
17         25         33

最新更新