2009-10-09 75 views
5

有人可以指出我在這裏做錯了嗎?python numpy savetxt

import numpy as np 

a = np.array([1,2,3,4,5],dtype=int) 
b = np.array(['a','b','c','d','e'],dtype='|S1') 

np.savetxt('test.txt',zip(a,b),fmt="%i %s") 

輸出是:

Traceback (most recent call last): 
    File "loadtxt.py", line 6, in <module> 
    np.savetxt('test.txt',zip(a,b),fmt="%i %s") 
    File "/Users/tom/Library/Python/2.6/site-packages/numpy/lib/io.py", line 785, in savetxt 
    fh.write(format % tuple(row) + '\n') 
TypeError: %d format: a number is required, not numpy.string_ 

回答

12

你需要以不同的方式構建你數組:

z = np.array(zip([1,2,3,4,5], ['a','b','c','d','e']), dtype=[('int', int), ('str', '|S1')]) 
np.savetxt('test.txt', z, fmt='%i %s') 

當你傳遞一個序列,savetext執行asarray(sequence) call並且結果數組的類型爲|S4,即所有元素都是字符串!這就是爲什麼你看到這個錯誤。

1

我想你所遇到的問題是要傳遞的元組通過格式化字符串,它不能與%I解釋的元組。嘗試使用FMT =「%s」時,假設這是你在找什麼作爲輸出:

1 a 
2 b 
3 c 
4 d 
5 e 
+0

這只是錯誤的。 'fmt =「%s」'工作原因完全不同,'fmt =「%s%s」'也可以,順便說一句。 – SilentGhost 2009-10-09 17:34:21

+0

你是對的,只要我發佈,我意識到它的工作,但不是因爲我的想法。我的錯。 SilentGhost的帖子好多了。謝謝。 – dwelch 2009-10-09 17:40:51

4

如果你想保存一個CSV文件,您還可以使用該功能rec2csv(包含在matplotlib.mlab)

>>> from matplotlib.mlab import rec2csv 
>>> rec = array([(1.0, 2), (3.0, 4)], dtype=[('x', float), ('y', int)]) 
>>> rec = array(zip([1,2,3,4,5], ['a','b','c','d','e']), dtype=[('x', int), ('y', str)]) 
>>> rec2csv(rec, 'recordfile.txt', delimiter=' ') 

希望,有一天pylab的開發商將實行寫作的CSV文件一個體面的支持。