Johnny Brofish Johnny Brofish - 4 months ago 77
Python Question

write numpy array to CSV with row indices and header

I have a simple 1 column numpy array.

[14
21
13
56
12]

I want to write to a CSV that includes the column along with row indices and a header. I found this function

numpy.savetxt("foo.csv", values, header="Id,Values", delimiter=",")


I'm not sure how to add the indices (1,2,3,4,5). Also, my header turns out to be "#Id,Values". I'm not sure where the # came from. This is what I get

# Id,Values
14
21
13
56
12


I want something like this

Id,Values
1,14
2,21
3,13
4,56
5,12

Answer

There may be a better way but I don't think you can do it directly with numpy.savetxt:

import  numpy as np

arr = np.array([14 ,21, 13, 56, 12])
np.savetxt("foo.csv", np.dstack((np.arange(1, arr.size+1),arr))[0],"%d,%d",header="Id,Values")

*The # is the default behaviour as documented:

String that will be prepended to the header and footer strings, to mark them as comments. Default: ‘# ‘, as expected by e.g. numpy.loadtxt.*

You could use comments="" but it is there for a reason.