6

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
3
  • why are you writing two column names and using a delimiter for a single column? Commented Jul 23, 2015 at 21:51
  • edited with desired output Commented Jul 23, 2015 at 21:52
  • looks like a Kaggle competition csv Commented Jan 3, 2019 at 17:18

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

4
    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.

Comments

2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.