Formatting a NumPy array

后端 未结 2 1699
暗喜
暗喜 2021-01-16 18:57

I want this:

        SP,1,2,3
        1,1.000000e+00,2.000000e+00,3.000000e+00
        2,1.630000e+01,1.990000e+01,1.840000e+01
        3,1.630000e+01,1.9900         


        
相关标签:
2条回答
  • 2021-01-16 19:23

    A simple solution requires to create a temporary array with the same length as my_array and an extra column.

    temp = np.empty((my_array.shape[0], my_array.shape[1]+1))
    

    Then, fill the first column with the indices you want, and the last columns with your initial array:

    temp[:,1:] = my_array
    temp[:,0] = np.arange(1, len(my_array)+1)
    

    In order to write the header, you have to open the file in writing first. You can still pass the file object to np.savetxt, you just have to modify the format string so that your first column is written as int, the others as "%10.6e":

    with open('final.csv', 'w') as f:
        f.write("SP,1,2,3\n")
        np.savetxt(f, temp, fmt="%i,%10.6e,%10.6e,%10.6e",delimiter=",")
    

    A more interactive way to define your format string, depending on the number of columns of my_array is

    fmt = ",".join(["%i"] + ["%10.6e"] * my_array.shape[1])
    np.savetxt(f, temp, fmt=fmt, delimiter=",")
    
    0 讨论(0)
  • 2021-01-16 19:31

    How about something like:

     from cStringIO import StringIO
     from itertools import izip
    
     # savetxt into a string
     sio = StringIO()
     np.savetxt(sio, my_array, fmt="%10.6e", delimeter=',')
     data_lines = sio.getvalue().split('\n')
    
     with open('Final Array.csv', 'w') as f:
         f.write(header_string + '\n')
         for leftcol, main in izip(left_column, data_lines):
             f.write(leftcol + ',' + main)
    

    Or to do it without savetxt at all:

    with open('Final Array.csv', 'w') as f:
        f.write(header_string + '\n')
        for label, row in izip(left_column, my_array):
            f.write(str(label) + ',' + ','.join('%10.6e' % x for x in row) + '\n')
    
    0 讨论(0)
提交回复
热议问题