python numpy savetxt

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1544948/
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-11-03 22:32:25  来源:igfitidea点击:

python numpy savetxt

pythonnumpy

提问by astrofrog

Can someone indicate what I am doing wrong here?

有人可以指出我在这里做错了什么吗?

import numpy as np

a = np.array([1,2,3,4,5],dtype=int)
b = np.array(['a','b','c','d','e'],dtype='|S1')

np.savetxt('test.txt',zip(a,b),fmt="%i %s")

The output is:

输出是:

Traceback (most recent call last):
  File "loadtxt.py", line 6, in <module>
    np.savetxt('test.txt',zip(a,b),fmt="%i %s")
  File "/Users/tom/Library/Python/2.6/site-packages/numpy/lib/io.py", line 785, in savetxt
    fh.write(format % tuple(row) + '\n')
TypeError: %d format: a number is required, not numpy.string_

回答by SilentGhost

You need to construct you array differently:

您需要以不同的方式构造数组:

z = np.array(zip([1,2,3,4,5], ['a','b','c','d','e']), dtype=[('int', int), ('str', '|S1')])
np.savetxt('test.txt', z, fmt='%i %s')

when you're passing a sequence, savetextperforms asarray(sequence)calland resulting array is of type |S4, that is all elements are strings! that's why you see this error.

当您传递一个序列时,savetext执行asarray(sequence)调用并且结果数组的类型为|S4,即所有元素都是字符串!这就是您看到此错误的原因。

回答by dalloliogm

If you want to save a CSV file you can also use the function rec2csv (included in matplotlib.mlab)

如果你想保存一个 CSV 文件,你也可以使用函数 rec2csv(包含在 matplotlib.mlab 中)

>>> from matplotlib.mlab import rec2csv
>>> rec = array([(1.0, 2), (3.0, 4)], dtype=[('x', float), ('y', int)])
>>> rec = array(zip([1,2,3,4,5], ['a','b','c','d','e']), dtype=[('x', int), ('y', str)])
>>> rec2csv(rec, 'recordfile.txt', delimiter=' ')

hopefully, one day pylab's developers will implement a decent support to writing csv files.

希望有朝一日 pylab 的开发人员能够实现对编写 csv 文件的体面支持。

回答by dwelch

I think the problem you are having is that you are passing tuples through the formating string and it can't interpret the tuple with %i. Try using fmt="%s", assuming this is what you are looking for as the output:

我认为您遇到的问题是您通过格式化字符串传递元组,并且它无法用 %i 解释元组。尝试使用 fmt="%s",假设这是您要查找的输出:

1 a
2 b
3 c
4 d
5 e