将标题添加到Numpy数组

Eri*_*bar 11 python numpy python-3.x

我有一个数组,我想添加一个标题.

这就是我现在拥有的:

0.0,1.630000e+01,1.990000e+01,1.840000e+01
1.0,1.630000e+01,1.990000e+01,1.840000e+01
2.0,1.630000e+01,1.990000e+01,1.840000e+01
Run Code Online (Sandbox Code Playgroud)

这就是我要的:

SP,1,2,3
0.0,1.630000e+01,1.990000e+01,1.840000e+01
1.0,1.630000e+01,1.990000e+01,1.840000e+01
2.0,1.630000e+01,1.990000e+01,1.840000e+01
Run Code Online (Sandbox Code Playgroud)

注意:"SP"将始终为1,后跟可能不同的列编号

这是我现有的代码:

fmt = ",".join(["%s"] + ["%10.6e"] * (my_array.shape[1]-1))

np.savetxt('final.csv', my_array, fmt=fmt,delimiter=",")
Run Code Online (Sandbox Code Playgroud)

mak*_*ghi 38

从Numpy 1.7.0开始,为了这个目的,numpy.savetxt中添加了三个参数:header,footer和comments.因此,您可以轻松地将代码编写为:

import numpy
a = numpy.array([[0.0,1.630000e+01,1.990000e+01,1.840000e+01],
                 [1.0,1.630000e+01,1.990000e+01,1.840000e+01],
                 [2.0,1.630000e+01,1.990000e+01,1.840000e+01]])
fmt = ",".join(["%s"] + ["%10.6e"] * (a.shape[1]-1))
numpy.savetxt("temp", a, fmt=fmt, header="SP,1,2,3", comments='')
Run Code Online (Sandbox Code Playgroud)


use*_*342 16

注意:这个答案是为numpy的旧版本编写的,在编写问题时是相关的.凭借现代的numpy,makhlaghi的答案提供了更优雅的解决方案.

既然numpy.savetxt也可以写入文件对象,你可以自己打开文件并在数据前写下你的标题:

import numpy
a = numpy.array([[0.0,1.630000e+01,1.990000e+01,1.840000e+01],
                 [1.0,1.630000e+01,1.990000e+01,1.840000e+01],
                 [2.0,1.630000e+01,1.990000e+01,1.840000e+01]])
fmt = ",".join(["%s"] + ["%10.6e"] * (a.shape[1]-1))

# numpy.savetxt, at least as of numpy 1.6.2, writes bytes
# to file, which doesn't work with a file open in text mode.  To
# work around this deficiency, open the file in binary mode, and
# write out the header as bytes.
with open('final.csv', 'wb') as f:
  f.write(b'SP,1,2,3\n')
  #f.write(bytes("SP,"+lists+"\n","UTF-8"))
  #Used this line for a variable list of numbers
  numpy.savetxt(f, a, fmt=fmt, delimiter=",")
Run Code Online (Sandbox Code Playgroud)