Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

list - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...