从python numpy数组中写入逗号分隔值

Joh*_*ohn 4 python csv numpy

我正在创建一个自定义文件编写器.我需要写出我的数组的值,逗号分隔成文件中的一行.我可以做以下事情:

def as_csv(array):

    return ','.join([str(i) for i in array]) + '\n'
Run Code Online (Sandbox Code Playgroud)

然后:

outfile.write(my_header)
outfile.write(other_stuff)
outfile.write(as_csv(array))
Run Code Online (Sandbox Code Playgroud)

但我想知道这是否是最有效的方法,或者是否有更好的方法使用numpy.array_str或numpy.array_repr方法.

jor*_*ris 6

您还可以使用内置的numpy方法np.savetxt:http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html

np.savetxt(outfile, array, delimiter=',')
Run Code Online (Sandbox Code Playgroud)