13

我有一个要为其添加标头的数组。

这就是我现在拥有的:

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

这就是我要的:

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

注意:“SP”总是第一个,后面是列的编号,可能会有所不同

这是我现有的代码:

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

np.savetxt('final.csv', my_array, fmt=fmt,delimiter=",")
4

2 回答 2

42

从 Numpy 1.7.0 开始,为了这个目的,已经在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("temp", a, fmt=fmt, header="SP,1,2,3", comments='')
于 2013-05-13T10:40:01.127 回答
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=",")
于 2012-09-01T07:27:39.373 回答