So I've a 2D-array looking like this:
[[1 0]
[2 0]
[3 0]
[4 0]
...
and I want to save it to a csvfile, I know that I must use to_csv to do so.
So I tried doing : np.savetxt("file.csv",array,delimiter=',',fmt='%d,%d'), %d is to store data as int not as the default format But my csv file only contains the first column and not the column of zero.
CodePudding user response:
Are you sure array
is what you claim? If I make it fresh:
In [234]: arr = np.array([[1, 0],
...: [2, 0],
...: [3, 0],
...: [4, 0]])
In [235]: arr
Out[235]:
array([[1, 0],
[2, 0],
[3, 0],
[4, 0]])
Your savetxt
works fine (the delimiter parameter isn't needed since you included it in the fmt):
In [237]: np.savetxt("file.csv",arr,delimiter=',',fmt='%d,%d')
In [238]: !more file.csv
1,0
2,0
3,0
4,0
CodePudding user response:
You do not have to use to_csv
. You'd probably benefit from coding your own. Writing from a numpy array (or any other simple data structure) to a csv file is only a few lines of code.
General structure...
Use a context manager to open the file in write mode...
with open('my_csv.csv', 'w') as f:
make a loop in there to loop over the rows in your array.
write the row with commas between the elements by converting the elements to strings and writing them with another loop (or with a join
command)
write a newline character to start the next row.
Give it a try. Comment back if you are stuck.