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

问题描述 投票:0回答:2

这是一个非常基本的代码,可以实现我想要的功能......除了文本文件的写入之外。

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_[]
,并且 will 写入列 if 我表达了命令中的每次迭代。即:
np.c_[a[0],a[1]]
等等。问题是,如果我的
i
j
值都非常大怎么办?遵循这种方法是不合理的。

python python-2.7 numpy for-loop
2个回答
1
投票

因此运行会产生:

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

您为每个

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


0
投票

您可以使用 file.write(' ') 在目标 for 循环内的 numpy.savetxt() 之后来分隔行。

例如:

import numpy as np
for i in range(2):
    f = open(f'./test.txt', 'a')
    np.savetxt(f, np.array([i,i+1]).transpose(), newline=' ')
    f.write('\n')
    f.close()

这将在文本文件中产生以下结果:

0.000000000000000000e+00 1.000000000000000000e+00 
1.000000000000000000e+00 2.000000000000000000e+00

使用 numpy.load() 加载文本文件后,您将得到一个 2×2 numpy 数组:

with open('./test.txt', 'r') as f:
    test_array = np.loadtxt(f)
print(test_array)
© www.soinside.com 2019 - 2024. All rights reserved.