如何使用 python numpy.savetxt 将字符串和浮点数写入 ASCII 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16621351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:10:19  来源:igfitidea点击:

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

pythonlistnumpyoutput

提问by Victor

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.

我想将这两个列表堆叠在一起,并以列的形式将它们写入一个文本文件;因此,我想使用numpy.savetxt(如果可能)来做到这一点。

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?

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

采纳答案by joris

You have to specify the format (fmt) of you data in savetxt, in this case as a string (%s):

您必须在 中指定数据的格式 ( fmt) savetxt,在本例中为字符串 ( %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.

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

回答by divenex

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.

当前接受的答案实际上并未解决该问题,该问题询问如何保存包含字符串和浮点数的列表。为了完整起见,我提供了一个完整的示例,该示例基于@joris 评论中给出的链接,并进行了一些修改。

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 abstructured 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.

更新:这个例子在 Python 3 中也能正常工作,在创建结构化数组时使用'U6'Unicode 字符串dtype而不是字节字符串。后一种 dtype 可以在 Python 2.7 中工作,但会像在 Python 3 中一样编写字符串。ab'S6'b'NAME_1'