2017-02-23 60 views
0

我有一個<class 'numpy.ndarray'>對象,我希望將它保存在txt文件中。該物體具有尺寸(形狀)(130, 118, 118)和尺寸1810120將numpy ndarray保存爲一個txt文件

當我嘗試使用np.savetxt(f, object, delimiter=' ', fmt='1.10f')f = open('test.txt', 'wb')我收到錯誤

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "C:\Users\G****\Anaconda3\lib\site-packages\numpy\lib\npyio.py", line 1139, in savetxt 
    raise error 
ValueError: fmt has wrong number of % formats: 1.10f 

我試過1的F各種組合,但沒有工作過。建議任何人?

UPDATE: 以下從意見建議波紋管,並添加fmt='%1.10f' 後,我收到這樣的:

Traceback (most recent call last): 
    File "C:\Users\G****\Anaconda3\lib\site-packages\numpy\lib\npyio.py", line 1158, in savetxt 
    fh.write(asbytes(format % tuple(row) + newline)) 
TypeError: only length-1 arrays can be converted to Python scalars 

During handling of the above exception, another exception occurred: 

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "C:\Users\G****\Anaconda3\lib\site-packages\numpy\lib\npyio.py", line 1162, in savetxt 
    % (str(X.dtype), format)) 
TypeError: Mismatch between array dtype ('int8') and format specifier ('%1.10f...... the '%1.10f goes on for quite a while) 
+0

嘗試:'fmt ='%1.10f'' –

回答

1

嘗試增加%,例如使用fmt='%1.10f'。請參閱here

更新:

import numpy as np 

obj = np.random.randint(10, size=(3, 4, 5), dtype=np.int8) # example array 

with open('test.txt', 'wb') as f: 
    np.savetxt(f, np.column_stack(obj), fmt='%1.10f') 

請注意,在最後一行的np.column_stack(obj)和閱讀this找出爲什麼它被用在這裏。但是,如果您的numpy數組包含整數,您可能需要使用fmt='%s'。此外,np.row_stack(obj)可能是一個有用的替代方案,具體取決於文件的外觀。

+0

謝謝!你能再次檢查我編輯的答案嗎? – Jespar

+0

你的numpy數組是8位整數的元素嗎? –

+0

是的,的確如此。這是否意味着我無法拯救他們? – Jespar