簡體   English   中英

格式化numpy數組並保存為* .txt

[英]Formatting numpy array and save to a *.txt

我想格式化一個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()

你覺得那樣好嗎?!

相當簡單:

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

你可以通過構造一個大字符串並在最后編寫它來將寫入數量進一步減少到一個,但是在這將是真正有益的情況下(即一個巨大的數組),你會遇到內存問題,從而構建一個巨大的弦。 無論如何,這取決於你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM