Skip to content Skip to sidebar Skip to footer

Formatting A Numpy Array

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.990000e+01,1.840000e+01

Solution 1:

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

Solution 2:

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

 withopen('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:

withopen('Final Array.csv', 'w') as f:
    f.write(header_string +'\n')
    for label, rowin izip(left_column, my_array):
        f.write(str(label) +','+','.join('%10.6e'% x for x inrow) +'\n')

Post a Comment for "Formatting A Numpy Array"