将numpy中的2D数组保存到文本文件

7

我使用

np.savetxt('file.txt', array, delimiter=',')

将数组保存到以逗号分隔的文件中。它看起来像这样:

1, 2, 3
4, 5, 6
7, 8, 9

我该如何将数组以numpy格式保存到文件中,使其外观与原数组一致?换句话说,它应该是这样的:
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]

5
你为什么要那样保存它?这只会让你在想要使用数据时阅读起来更加困难。 - MattDMo
@MattDMo,我想在其他地方使用数组,但只能使用stdin而不是从磁盘读取。我计划使用天真的复制+粘贴方法。 - ChuNan
4个回答

7
In [38]: x = np.arange(1,10).reshape(3,3)    

In [40]: print(np.array2string(x, separator=', '))
[[1, 2, 3],
 [4, 5, 6],
 [7, 8, 9]]

将NumPy数组x保存到文件中:

np.set_printoptions(threshold=np.inf, linewidth=np.inf)  # turn off summarization, line-wrapping
with open(path, 'w') as f:
    f.write(np.array2string(x, separator=', '))

@DSM:谢谢,我只是不知道它在那里。 - unutbu
谢谢您的回复。当我尝试在tmp = np.array2string(x, separator=', ')上使用savetxt时,它会给出“元组索引超出范围”的错误。您能否请展示一下如何将结果保存到文本文件中?谢谢。 - ChuNan
@ChuNan:我添加了一些代码来展示如何将x保存到文件中。这对于中等大小的数组应该是有效的。然而,一个缺点是如果x非常大,np.array2string会生成一个巨大的字符串。这不利于内存。在这种情况下,最好遍历x的行,并将它们分块打印出来。 - unutbu
它适用于我的情况。非常感谢您的帮助! - ChuNan

3
您可以使用第一种格式进行复制和粘贴:
>>> from io import BytesIO
>>> bio = BytesIO('''\
... 1, 2, 3
... 4, 5, 6
... 7, 8, 9
... ''') # copy pasted from above
>>> xs = np.loadtxt(bio, delimiter=', ')
>>> xs
array([[ 1.,  2.,  3.],
       [ 4.,  5.,  6.],
       [ 7.,  8.,  9.]])

2
import sys

file = "<you_file_dir>file.txt"

sys.stdout = open(file, 'w')

d = [1,2,3,4,5,6,7,8,9]
l__d1 = d[0:3]
l__d2 = d[3:6]
l__d3 = d[6:9]

print str(l__d1) + '\n' + str(l__d2) + '\n' + str(l__d3)

0
import numpy as np
def writeLine(txt_file_path, txtArray: list):
   l = len(txtArray)
   counter = 0
   with open(txt_file_path, 'a', encoding='utf-8') as f:
       for item in txtArray:
           counter += 1
           row = [str(x) for x in item]
           fstr = '\t'.join(row)+'\n' if counter<l else '\t'.join(row)
           f.writelines(fstr)

x = np.arange(16).reshape(4,4)
writeLine('a.txt',x)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接