Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write numpy array to CSV with row indices and header

Tags:

python

numpy

I have a numpy array.

values = np.array([14, 21, 13, 56, 12])

I want to write values in one column of a CSV file, the row indices in another column, 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
like image 310
Johnny Brofish Avatar asked Jul 23 '15 21:07

Johnny Brofish


3 Answers

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.

like image 66
Padraic Cunningham Avatar answered Oct 13 '22 11:10

Padraic Cunningham


    import pandas as pd
dt = pd.DataFrame(data=a)
dt.to_csv('/test_csv.csv', mode='a', index=True)

you can use to_csv function in pandas by explicitly set index=True or default.

like image 41
pcc426 Avatar answered Oct 13 '22 09:10

pcc426


You can do it with csv fairly easily, assuming you're ok with a 0-based index:

import numpy as np
import csv

a = np.array([14, 21, 13, 56, 12])

with open('out.csv', 'wb') as fh:
    writer = csv.writer(fh, delimiter=',')
    writer.writerow(['id','val'])
    writer.writerows(enumerate(a))
like image 24
AMacK Avatar answered Oct 13 '22 10:10

AMacK