How to Use Python Numpy.Savetxt to Write Strings and Float Number to an Ascii File

How to use python numpy.savetxt to write strings and float number to an ASCII file?

You have to specify the format (fmt) of you data in savetxt, in this case as a string (%s):

num.savetxt('test.txt', DAT, delimiter=" ", fmt="%s") 

The default format is a float, that is the reason it was expecting a float instead of a string and explains the error message.

Write strings and float number to an ASCII file with python

The solution that I found was to use the CSV File Reading and Writing library.

I just added the library in the beginning "import csv" and then added the following lines along the code.

First, in the begging, I needed to set the file directory to save the data.

#Opening the file to save the data
write_path = main_directory + "\\Dados\\Exportados\\" + "file_name" + ".csv"
file = open(write_path, 'a')
writer = csv.writer(file)

The 'a' parameter allows you to append to the end of the file

Then, in the step that I wanted the data to be saved, I added the following line:

#Writing to the file
writer.writerow([mes_pelo_nome, ano_pelo_nome, dia_pelo_nome, mascara, media])

In the end, I added the following line to close the file:

file.close()

Writing both float and integer on a text file from one numpy array

Try fmt="%.8g". It is not the same as "%.8f" for all floating point values (e.g. for very small values, it uses exponential notation), but it might work for the cases you have.
(See the table at https://docs.python.org/2/library/string.html#format-specification-mini-language with the floating point types--scroll down a bit--for an explanation of the difference between the f and g formats.)

In [188]: x
Out[188]:
array([[ 0.20134635, -9999. ],
[ 0.9287082 , 0.00000123],
[ 0.77482316, 0.27246281],
[ 0.40529746, 0.41133371]])

In [189]: np.savetxt("xf.dat", x, fmt="%.8f")

In [190]: np.savetxt("xg.dat", x, fmt="%.8g")

In [191]: !cat xf.dat
0.20134635 -9999.00000000
0.92870820 0.00000123
0.77482316 0.27246281
0.40529746 0.41133371

In [192]: !cat xg.dat
0.20134635 -9999
0.9287082 1.2345679e-06
0.77482316 0.27246281
0.40529746 0.41133371

Here's the actual value of x[1,1]:

In [193]: x[1,1]
Out[193]: 1.23456789e-06

Alternatively, take a look at this answer to a similar question: How to format in numpy savetxt such that zeros are saved only as "0"

python numpy.savetext a matrix with mixed format

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.

Which argument is required for np.savetxt to output float data?

From documentation , you can clearly see that np.savetext requires an array_like object as the second argument.

You can try converting line into an array before saving , something like -

np.savetxt('inside.txt', np.array(line.split(" ")), delimiter=" ", fmt="%s")

TypeError when using np.savetxt to save a collection of three lists to .csv

I can replicate your problem with:

x=['one','two','three']
y=['a','b','c']
z=['1','2','3']
zz=list(zip(x,y,z)) # py3

zz
Out[58]: [('one', 'a', '1'), ('two', 'b', '2'), ('three', 'c', '3')]

za=np.array(zz) # make list an array; note the dtype

za
Out[60]:
array([['one', 'a', '1'],
['two', 'b', '2'],
['three', 'c', '3']],
dtype='<U5')

np.savetxt('test',zz)
-------------------------------------------------------------------
...
TypeError: Mismatch between array dtype ('<U5') and format specifier ('%.18e %.18e %.18e')

Same sort of error when trying to write strings as floats. But if I change the format to a string one:

np.savetxt('test',za,fmt='%10s')

cat test
one a 1
two b 2
three c 3

If your inputs really are numbers then you could convert the string to numbers while building the lists.

Another option is to write the list to the csv directly (with file write) or with the Python csv module.



Related Topics



Leave a reply



Submit