Reputation: 1544
As simple as it seems, I could not find any solution for my question online. Basically, I have two arrays a
and b
that I want to save to a csv file. It will be two columns. I want to add the column names as well. Below code I use to dump arrays to a csv.
from np import array, savetxt
a = array([1,2,3,4])
b = array([5,6,7,8])
savetxt('submission2.csv', zip(a,b), delimiter=',', fmt='%f')
How would I add column names? I would like the csv file to look like
Name1 Name2
1 5
2 6
3 7
4 8
It is so strange that this option is not in the savetxt
function. header
option does do it because it just pastes a comment into the first cell. Thanks.
Edit: Arrays
Upvotes: 26
Views: 68227
Reputation: 1555
I have found a solution for saving multiple numpy 1D arrays as columns:
import numpy as np
data = []
for i in single_np_arrays:
data.append(i)
data = np.array(data).T #transpose the array to have proper columns
np.savetxt('columns_from_np_arrays.csv',data,delimiter=',')
Upvotes: 0
Reputation: 782
Note that savetxt
(and loadtxt
) also takes file handles.
Hence if you want a more advanced header you can do this:
a = array([1,2,3,4])
b = array([5,6,7,8])
with open('submission2.csv','w') as f:
f.write('# This is a very complex header\n')
f.write('A,B\n')
savetxt(f, zip(a,b), delimiter=',', fmt='%f')
Or, as has already been noted, use the header=str(...)
argument.
Upvotes: 2
Reputation: 174624
Use the header
option, like this:
>>> import numpy
>>> a = numpy.array([[1,2],[3,4],[5,6]])
>>> numpy.savetxt("foo.csv", a, delimiter=',', header="A,B", comments="")
The resulting file looks like this:
A,B
1.000000000000000000e+00,2.000000000000000000e+00
3.000000000000000000e+00,4.000000000000000000e+00
5.000000000000000000e+00,6.000000000000000000e+00
Upvotes: 20
Reputation: 31662
You can do it with pandas package easily:
import pandas as pd
import numpy as np
a = np.array([1,2,3,4])
b = np.array([5,6,7,8])
df = pd.DataFrame({"name1" : a, "name2" : b})
df.to_csv("submission2.csv", index=False)
Upvotes: 35
Reputation: 19733
you can do like this:
import np import array, savetxt
a = array([1,2,3,4])
b = array([5,6,7,8])
f = open("submission2.csv", "w")
f.write("{},{}\n".format("Name1", "Name2"))
for x in zip(a, b):
f.write("{},{}\n".format(x[0], x[1]))
f.close()
Upvotes: 1