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

4

87

I have a set of lists that contain both strings and float numbers, such as:

import numpy as num

NAMES  = num.array(['NAME_1', 'NAME_2', 'NAME_3'])
FLOATS = num.array([ 0.5    , 0.2     , 0.3     ])

DAT =  num.column_stack((NAMES, FLOATS))

I want to stack these two lists together and write them to a text file in the form of columns; therefore, I want to use numpy.savetxt (if possible) to do this.

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

When I do this, I get the following error:

>>> num.savetxt('test.txt', DAT, delimiter=" ") 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/numpy-1.8.0.dev_9597b1f_20120920-py2.7-macosx-10.8-x86_64.egg/numpy/lib/npyio.py", line 1047, in savetxt
    fh.write(asbytes(format % tuple(row) + newline))
TypeError: float argument required, not numpy.string_

The ideal output file would look like:

NAME_1    0.5
NAME_2    0.2
NAME_3    0.3

How can I write both strings and float numbers to a text file, possibly avoiding using csv ( I want to make if readable for other people )? Is there another way of doing this instead of using numpy.savetxt?

Nectar answered 18/5, 2013 at 6:20 Comment(0)
P
147

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.

Poock answered 18/5, 2013 at 8:37 Comment(2)
And what happens if I want to format the numbers? How can I give some format to the numbers only?Forecourt
You can give different formats to different columns, like fmt="%f %i". But if you want to combine it with strings as in the example above, you will need a structured array (see here). In this example, the int is converted to a string, and then formatting as an int is not possible anymore.Poock
P
40

The currently accepted answer does not actually address the question, which asks how to save lists that contain both strings and float numbers. For completeness I provide a fully working example, which is based, with some modifications, on the link given in @joris comment.

import numpy as np

names  = np.array(['NAME_1', 'NAME_2', 'NAME_3'])
floats = np.array([ 0.1234 ,  0.5678 ,  0.9123 ])

ab = np.zeros(names.size, dtype=[('var1', 'U6'), ('var2', float)])
ab['var1'] = names
ab['var2'] = floats

np.savetxt('test.txt', ab, fmt="%10s %10.3f")

Update: This example also works properly in Python 3 by using the 'U6' Unicode string dtype, when creating the ab structured array, instead of the 'S6' byte string. The latter dtype would work in Python 2.7, but would write strings like b'NAME_1' in Python 3.

Poultry answered 4/2, 2016 at 18:42 Comment(1)
What if I had a bidimensional floats array and wanted to print each name with its correspondent array? Would the only way be adding all the rows manually or is there a simpler way to do that? Expected output: NAME_1 0.1 0.2 0.3Kopeisk
K
0
import numpy as np

a = 'a,b,c'

b = [[1, 2, 3], [4, 5, 6]]

with open('test.csv', 'w') as f:
    f.writelines(a + '\n')
    np.savetxt(f, b, delimiter=',', fmt='%f')



The output file would look like this:
a,b,c
1.000000,2.000000,3.000000
4.000000,5.000000,6.000000

This example is for numpy.savetxt to write strings and float numbers to file, especially for strings that are written in rows.

Kronfeld answered 10/3, 2022 at 2:12 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Connective
I
0

There is actually a header parameter:

np.savetxt(file, data, delimiter=',', header='TimeStamp,X,Z', fmt='%s,%.2f,%d')
    
Inessential answered 19/12, 2023 at 14:46 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Connective

© 2022 - 2024 — McMap. All rights reserved.