python numpy savetxt

ast*_*rog 5 python numpy

有人能说出我在做错了吗?

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")
Run Code Online (Sandbox Code Playgroud)

输出是:

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_
Run Code Online (Sandbox Code Playgroud)

Sil*_*ost 12

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

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')
Run Code Online (Sandbox Code Playgroud)

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