Formatting a NumPy array

后端 未结 2 1700
暗喜
暗喜 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: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')
    

提交回复
热议问题