Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: Mismatch between array dtype ('float64') and format specifier

I have a numpy array with dimension 1000*30*150. I am trying to save it as txt file. So far I have tried this

np.savetxt("test.txt", mydata, fmt='%.5f', delimiter=",")
#and 
with open('test.txt', 'w') as f:
    for row in mydata:
        np.savetxt(f, row, delimiter=',', fmt='%.5f')

both method give me error

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/numpy/lib/npyio.py", line 1254, 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):


        np.savetxt("test.txt", train, fmt='%.5f', delimiter=",")
      File "/usr/local/lib/python3.5/dist-packages/numpy/lib/npyio.py", line 1258, in savetxt
        % (str(X.dtype), format))
    TypeError: Mismatch between array dtype ('float64') and format specifier ('%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f,%.5f')
like image 758
Test Test Avatar asked Aug 09 '17 01:08

Test Test


1 Answers

The problem is your array is 3 dimensional and can't be saved in a 2 dimensional format. Either reshape it, so that it is 2d:

mydata = mydata.reshape(mydata.shape[0],mydata.shape[1]*mydata.shape[2])
np.savetxt('text.txt',mydata,fmt='%.5f',delimiter=',')

or if you do not need to read it as a text file and want to just reload it later in python use:

np.save('text.npy',mydata)
like image 65
DJK Avatar answered Nov 09 '22 23:11

DJK