向Numpy数组添加标题

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

5
你已经在这里得到了答案(http://stackoverflow.com/questions/12218945/formatting-numpy-array/12219132#12219132),为什么还要再问一遍呢? (将链接和问题内容翻译并简化,不改变原意) - Pierre GM
3个回答

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

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

使用这段代码时,我得到了以下错误:文件“C:\ Python32 \ lib \ site-packages \ numpy \ lib \ npyio.py”,第1009行,在savetxt函数中: fh.write(asbytes(format % tuple(row) + newline)) TypeError: 必须是str类型,而不是bytes类型 - Eric Escobar
我已经纠正了答案,使其在Python 3中可用,并测试了Python 3.2.3。 - user4815162342

0

使用savezsavez_compressed函数,也可以将除了numpy数组以外的其他内容保存到文件中。使用load函数,您可以像解压缩字典一样检索所有数据。

import numpy as np

np.savez("filename.npz", array_to_save=np.array([0.0, 0.0]), header="Some header")

data = np.load("filename.npz")
array = data["array_to_save"]
header = str(data["header"])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接