本文介绍了如何使用 python numpy.savetxt 将字符串和浮点数写入 ASCII 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组包含字符串和浮点数的列表,例如:

import numpy as numNAMES = num.array(['NAME_1', 'NAME_2', 'NAME_3'])浮点数 = num.array([ 0.5 , 0.2 , 0.3 ])DAT = num.column_stack((NAMES, FLOATS))

我想把这两个列表堆叠在一起,以列的形式写入一个文本文件;因此,我想使用 numpy.savetxt(如果可能)来执行此操作.

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

执行此操作时,出现以下错误:

>>>num.savetxt('test.txt', DAT, delimiter="")回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中文件/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",第1047行,在savetxt中fh.write(asbytes(format % tuple(row) + newline))类型错误:需要浮点参数,而不是 numpy.string_

理想的输出文件如下:

NAME_1 0.5NAME_2 0.2NAME_3 0.3

如何将字符串和浮点数写入文本文件,可能避免使用 csv(如果其他人可读,我想制作)?除了使用 numpy.savetxt 之外,还有其他方法吗?

解决方案

您必须在 savetxt 中指定数据的格式 (fmt),在这种情况下为一个字符串(%s):

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

默认格式是浮点数,这就是它期望浮点数而不是字符串的原因,并解释了错误消息.

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?

解决方案

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.

这篇关于如何使用 python numpy.savetxt 将字符串和浮点数写入 ASCII 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-05 10:09