Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 414
Victor Avatar asked May 18 '13 06:05

Victor


People also ask

How do you write NumPy array to text file in Python?

Let us see how to save a numpy array to a text file. Creating a text file using the in-built open() function and then converting the array into string and writing it into the text file using the write() function. Finally closing the file using close() function.

Can you use NumPy with strings?

The elements of a NumPy array, or simply an array, are usually numbers, but can also be boolians, strings, or other objects.

How do I append a NumPy array to a text file?

The NumPy module savetxt() method is used to append the Numpy array at the end of the existing csv file with a single format pattern fmt = %s. We will open CSV file in append mode and call the savetxt() method to writes rows with header. Second call the savetxt() method to append the rows.

How do I save an array to a text file in Python?

We can save an array to a text file using the numpy. savetxt() function. The function accepts several parameters, including the name of the file, the format, encoding format, delimiters separating the columns, the header, the footer, and comments accompanying the file.


2 Answers

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.

like image 133
joris Avatar answered Sep 23 '22 13:09

joris


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.

like image 26
divenex Avatar answered Sep 22 '22 13:09

divenex