我不知道你嘗試過什麼,但你需要使用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
不要忘了'分隔符='\ t'' –
大謝謝!還有一件事 - >我怎麼能在第三行(在數組開始之前)寫一行不以#開始的行(在我的情況下,它只是一個數字) – Matias
再次感謝您 - 我嘗試了您的附錄 - 但我錯過了extra_num :)。如果可能的話,代碼應該如下所示:第一行「#Filexy;第二行」#time operation1 operation2;第三行「42(沒有#);第四 - 結束:數組。非常感謝你的幫助! – Matias