3

I am trying to save as text a matrix which has in each row 288 float and 1 string at the end, i've used the savetxt like this:

np.savetxt('name', matrix, delimiter='  ', header='string', comments='', fmt= '%3f'*288 + '%s')

but when I try to run the code it raises exceptions like this:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\numpy\lib\npyio.py", line 1371, in savetxt
    v = format % tuple(row) + newline
TypeError: must be real number, not numpy.str_

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\numpy\lib\npyio.py", line 1375, in savetxt
    % (str(X.dtype), format))
TypeError: Mismatch between array dtype ('<U32') and format specifier ('%3f(repeated 288 times without spaces)%s')

I really can't understand where I am wrong.

p-a-o-l-o
  • 9,807
  • 2
  • 22
  • 35
francesco
  • 57
  • 2
  • 10
  • The error message shows you what it is trying to do. `fmt%tuple(matrix[0])`. Change your `fmt` to get that right. – hpaulj Apr 05 '18 at 12:22

1 Answers1

5

Your error message says that you are providing string data (dtype ('<U32')) -U32 stands for Unicode string- but your format specifier is floating numbers followed by a string ('%3f(repeated 288 times without spaces)%s').

Since your matrix is already string there is no point in trying to format it anyway. If you are not satisfied with the floating point digits you should probably format it before entering to this matrix.

So, in your case to just write your present matrix just use:

np.savetxt('name', matrix, delimiter='  ', header='string', comments='', fmt='%s')

which will treat each element as a string (which they actually are) and write it to the text file.

Also maybe this answer provide some clues if you are not satisfied.

Eypros
  • 5,370
  • 6
  • 42
  • 75
  • Thank you very much! now it works, i'll see if floating point data cause problems and in case i'll format them before enter the matrix as you suggest. – francesco Apr 05 '18 at 13:56