将标头添加到 Numpy 数组

新手上路,请多包涵

我有一个数组,我想为其添加标题。

这就是我现在所拥有的:

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

原文由 Eric Escobar 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 931
2 个回答

注意: 此答案是为较旧版本的 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=",")

原文由 user4815162342 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

原文由 makhlaghi 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题