Skip to main content
 首页 » 编程设计

python之如何让 python 的 np.savetxt 将循环的每次迭代保存在不同的列中

2025年04月02日1252php

这是一个非常基本的代码,可以满足我的要求...除了文本文件的编写。

import numpy as np 
 
f = open("..\myfile.txt", 'w') 
tst = np.random.random(5) 
tst2 = tst/3 
for i in range(3): 
    for j in range(5): 
        test = np.random.random(5)+j 
        a = np.random.normal(test, tst2) 
    np.savetxt(f, np.transpose(a), fmt='%10.2f') 
    print a 
f.close() 

此代码将在 for 循环的每次迭代后串联的单个列写入 .txt 文件。

我想要的是每次迭代的独立列。

如何做到这一点?

注意:我也使用了 np.c_[],将写入列如果我在命令。即:np.c_[a[0],a[1]] 等等。问题是,如果我的 i 和 j 值都非常大怎么办?遵循这种方法是不合理的。

请您参考如下方法:

所以运行产生:

2218:~/mypy$ python3 stack39114780.py  
[ 4.13312217  4.34823388  4.92073836  4.6214074   4.07212495] 
[ 4.39911371  5.15256451  4.97868452  3.97355995  4.96236119] 
[ 3.82737975  4.54634489  3.99827574  4.44644041  3.54771411] 
2218:~/mypy$ cat myfile.txt 
      4.13 
      4.35 
      4.92 
      4.62 
      4.07    # end of 1st iteration 
      4.40 
      5.15 
      4.98 
      3.97 
      .... 

你明白这是怎么回事吗?一次调用 savetxt 会写入一组行。对于像 a 这样的一维数组,它每行打印一个数字。 (transpose(a) 不执行任何操作)。

文件写入是逐行完成的,不能倒带加列。因此,要制作多列,您需要创建一个包含多列的数组。然后做一个savetxt。换句话说,在写入之前收集所有数据。

将你的值收集到一个列表中,制作一个数组,然后写下

alist = [] 
for i in range(3): 
    for j in range(5): 
        test = np.random.random(5)+j 
        a = np.random.normal(test, tst2) 
        alist.append(a) 
arr = np.array(alist) 
print(arr) 
np.savetxt('myfile.txt', arr, fmt='%10.2f') 

我得到 15 行 5 列,但您可以对其进行调整。

2226:~/mypy$ cat myfile.txt 
  0.74       0.60       0.29       0.74       0.62 
  1.72       1.62       1.12       1.95       1.13 
  2.19       2.55       2.72       2.33       2.65 
  3.88       3.82       3.63       3.58       3.48 
  4.59       4.16       4.05       4.26       4.39 

由于 arr 现在是 2d,np.transpose(arr) 做了一些有意义的事情——我会得到 5 行 15 列。

==================

与

for i in range(3): 
    for j in range(5): 
        test = np.random.random(5)+j 
        a = np.random.normal(test, tst2) 
    np.savetxt(f, np.transpose(a), fmt='%10.2f') 

您为每个 i 编写一次 a - 因此是 3 行。您丢弃了 4 次 j 迭代。在我的变体中,我收集了所有 a,因此得到 15 行。