[python] 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?

This question is related to python list numpy output

The answer is


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.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to numpy

Unable to allocate array with shape and data type How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function? Numpy, multiply array with scalar TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'" Pytorch tensor to numpy array Numpy Resize/Rescale Image what does numpy ndarray shape do? How to round a numpy array? numpy array TypeError: only integer scalar arrays can be converted to a scalar index

Examples related to output

How to create multiple output paths in Webpack config Where does the slf4j log file get saved? CMake output/build directory Suppress console output in PowerShell Output grep results to text file, need cleaner output How to use python numpy.savetxt to write strings and float number to an ASCII file? How to read a CSV file from a URL with Python? How can I suppress column header output for a single SQL statement? How to recover closed output window in netbeans? How can I see normal print output created during pytest run?