【问题标题】:Adding Header to Numpy array将标题添加到 Numpy 数组
【发布时间】:2012-08-26 17:36:00
【问题描述】:

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

这就是我现在拥有的:

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

【问题讨论】:

  • 你已经有了答案here,为什么还要问?

标签: python numpy python-3.x


【解决方案1】:

自 Numpy 1.7.0 以来,已将三个参数添加到 numpy.savetxt 正是为了这个目的:页眉、页脚和 cmets。所以你想要的代码可以很容易地写成:

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

【讨论】:

    【解决方案2】:

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

    由于numpy.savetxt也可以写入文件对象,所以你可以自己打开文件,在数据前写上你的header:

    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: must be str, not bytes @user4815162342
    • 我现在已经更正了在 Python 3 中工作的答案,并使用 Python 3.2.3 进行了测试。
    猜你喜欢
    • 2012-06-21
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    • 2011-02-10
    • 2014-03-05
    • 2017-12-27
    • 1970-01-01
    相关资源
    最近更新 更多