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
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.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With