2016-09-14 62 views
5

我需要將3個numpy數組寫入一個txt文件。該文件的頭部看起來像這樣:如何將numpy數組寫入.txt文件,從某一行開始?

#Filexy 
#time operation1 operation2 

的numpy的數組如下所示:

time = np.array([0,60,120,180,...]) 
operation1 = np.array([12,23,68,26,...)] 
operation2 = np.array([100,123,203,301,...)] 

最後,.txt文件應該是這樣的(分隔符應該是一個選項卡) :

#Filexy 
#time operation1 operation2 
0 12 100 
60 23 123 
120 68 203 
180 26 301 
.. ... ... 

我試過用「numpy.savetxt」 - 但我沒有得到我想要的格式。

非常感謝您的幫助!

回答

4

我不知道你嘗試過什麼,但你需要使用header參數np.savetxt。另外,你需要正確連接你的數組。最簡單的方法是使用np.c_,這會強制您的一維數組轉換爲二維數組,然後按您期望的方式將它們連接起來。

>>> time = np.array([0,60,120,180]) 
>>> operation1 = np.array([12,23,68,26]) 
>>> operation2 = np.array([100,123,203,301]) 
>>> np.savetxt('example.txt', np.c_[time, operation1, operation2], 
       header='Filexy\ntime operation1 operation2', fmt='%d', 
       delimiter='\t') 

example.txt現在包含:

# Filexy 
# time operation1 operation2 
0 12 100 
60 23 123 
120 68 203 
180 26 301 

還要注意的fmt='%d'使用情況,以獲得在輸出整數值。默認情況下,savetxt將保存爲浮點數,即使是整數數組也是如此。

關於分隔符,您只需要使用delimiter參數。這裏並不清楚,但實際上,列之間有標籤。例如,vim顯示我的選項卡使用點:

# Filexy 
# time operation1 operation2 
0· 12· 100 
60· 23· 123 
120·68· 203 
180·26· 301 

附錄:

如果您要添加頁眉陣列前添加一個額外的行,你最好創建一個自定義標題,完成你自己的評論角色。使用comment參數可防止savetxt增加額外的#'s。

>>> extra_text = 'Answer to life, the universe and everything = 42' 
>>> header = '# Filexy\n# time operation1 operation2\n' + extra_text 
>>> np.savetxt('example.txt', np.c_[time, operation1, operation2],  
       header=header, fmt='%d', delimiter='\t', comments='') 

產生

# Filexy 
# time operation1 operation2 
Answer to life, the universe and everything = 42 
0 12 100 
60 23 123 
120 68 203 
180 26 301 
+1

不要忘了'分隔符='\ t'' –

+0

大謝謝!還有一件事 - >我怎麼能在第三行(在數組開始之前)寫一行不以#開始的行(在我的情況下,它只是一個數字) – Matias

+0

再次感謝您 - 我嘗試了您的附錄 - 但我錯過了extra_num :)。如果可能的話,代碼應該如下所示:第一行「#Filexy;第二行」#time operation1 operation2;第三行「42(沒有#);第四 - 結束:數組。非常感謝你的幫助! – Matias

0

試試這個:

f = open(name_of_the_file, "a") 
np.savetxt(f, data, newline='\n') 
f.close() 
相關問題