将numpy数组格式化并保存为*.txt文件

3
我可以帮你进行翻译。需要将一个numpy数组格式化并保存为*.txt文件。 该numpy数组的样式如下:
a = [ 0.1   0.2   0.3   0.4   ... ] , [ 1.1   1.2   1.3   1.4   ... ] , ...

输出的*.txt文件应该是这样的:

0   1:0.1   2:0.2   3:0.3   4:0.4   ...
0   1:1.1   2:1.2   3:1.3   1:1.4   ...
...

不知道如何做。

谢谢。

嗯,Jaba,谢谢你。我稍微修改了你的答案。

import numpy as np

a = np.array([[1,3,5,6], [4,2,4,6], [6,3,2,6]])

ret = ""

for i in range(a.shape[0]):
    ret += "0 "
    for j in range(a.shape[1]):
        ret += " %s:%s" % (j+1,float(a[i,j])) #have a space between the numbers for better reading and i think it should starts with 1 not with 0 ?!
ret +="\n"

fd = open("output.sparse", "w")
fd.write(ret)
fd.close()
你觉得这样行吗?!
1个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
4
相对简单:
import numpy as np

a = np.array([[0.1, 0.2, 0.3, 0.4], [1.1, 1.2, 1.3, 1.4], [2.1, 2.2, 2.3, 2.4]])

with open("array.txt", 'w') as h:  
    for row in a:
        h.write("0")
        for n, col in enumerate(row):
            h.write("\t{0}:{1}".format(n+1, col))  # you can change the \t (tab) character to a number of spaces, if that's what you require
        h.write("\n")

输出:

0       1:0.1   2:0.2   3:0.3   4:0.4
0       1:1.1   2:1.2   3:1.3   4:1.4
0       1:2.1   2:2.2   3:2.3   4:2.4

我的原始示例涉及大量的磁盘写入。如果你的数组很大,这可能会非常低效。但是可以通过减少写入次数来降低它们的数量,例如:

with open("array.txt", 'w') as h:  
    for row in a:
        row_str = "0"
        for n, col in enumerate(row):
            row_str = "\t".join([row_str, "{0}:{1}".format(n+1, col)])
        h.write(''.join([row_str, '\n']))
你可以通过构建一个大字符串并在最后写入来进一步将写操作的数量减少到一个,但是如果这对于一个巨大的数组而言确实有益处,那么你会遇到从构建巨大的字符串中出现的内存问题。无论如何,这取决于你。

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