【问题标题】:how can I get python's np.savetxt to save each iteration of a loop in a different column?如何让 python 的 np.savetxt 将循环的每次迭代保存在不同的列中?
【发布时间】:2016-08-24 05:02:57
【问题描述】:

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

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

【问题讨论】:

  • 演示最后一个np.c_[] 位。这有什么不合理的地方?
  • 在这个小例子所涉及的实际代码中,我有 3 个嵌套的 for 循环,总共 804 次迭代,以我的小样本大小生成一个 17700 行的 .txt 文件。随着样本量的增加,迭代需求也会发生变化。这就是为什么它不合理。
  • 更详细地解释期望的文件布局。多少列,多少行?迭代与列或行的关系是什么?
  • 列数与迭代次数有关,行数与来源的数据点数有关。 @hpaulj 我喜欢您在下面使用 np.append 功能的示例,但是我还不能让它工作。请参阅 [stackoverflow.com/q/39010539/3920407] 了解正在使用的代码的更好示例。

标签: python python-2.7 numpy for-loop


【解决方案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')

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

【讨论】:

    猜你喜欢
    • 2018-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    相关资源
    最近更新 更多