Formatting a NumPy Array

I want it:

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 4,1.630000e+01,1.990000e+01,1.840000e+01 

I have the following code:

 np.savetxt("Final Array.csv", my_array, fmt="%10.6e", delimiter=',') 

He produces:

  1.000000e+00,2.000000e+00,3.000000e+00 1.630000e+01,1.990000e+01,1.840000e+01 1.630000e+01,1.990000e+01,1.840000e+01 1.630000e+01,1.990000e+01,1.840000e+01 

I already have arrays created for the top row and left column.

How can I format this so that I can correctly format the numbers, while remaining the largest column on the left, and the top row remains formatted as they are?

I use vstack and hstack to combine them, but "SP" also causes problems because it is not a float.

Can I possibly format them, convert everything to a string, concatenate and then savetxt?

0
source share
2 answers

For a simple solution, you need to create a temporary array with the same length as my_array , and an additional column.

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

Then fill the first column with the desired indexes and the last columns with your original array:

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

To write a title, you must first open the file in writing. You can still pass the file object to np.savetxt , you just need to change the format string so that your first column is written as int , the rest 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 of defining your format string, depending on the number of my_array columns,

 fmt = ",".join(["%i"] + ["%10.6e"] * my_array.shape[1]) np.savetxt(f, temp, fmt=fmt, delimiter=",") 
+2
source

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 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') 
+2
source

Source: https://habr.com/ru/post/924323/


All Articles