将标题添加到Numpy数组

时间:2012-08-31 22:23:02

标签: 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

这就是我想要的:

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”将始终为1,然后是可能变化的列的编号

这是我现有的代码:

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

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

2 个答案:

答案 0 :(得分:37)

自从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='')

答案 1 :(得分:16)

注意:这个答案是为numpy的旧版本编写的,在编写问题时是相关的。使用现代numpy,makhlaghi's answer提供了更优雅的解决方案。

由于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=",")