Reputation: 148
I have a 2D array from a function f.example
which returns me:
array([[ 0.0, 1.0, 2.0, 3.0 ],
[ 5.0, 1.0, 3.0, 3.0 ],
[ 1.0, 1.0, 3.0, 3.0 ]])
In fact I am able to write it to a csv file, but just not the way I want. Here is how the csv file should look like:
0.0 5.0 1.0
1.0 1.0 1.0
2.0 3.0 3.0
3.0 3.0 3.0
But this is how it looks now:
0.0 1.0 2.0 3.0
5.0 1.0 3.0 3.0
1.0 1.0 3.0 3.0
And the code that I have:
with open('example.csv', 'w') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(f.example)
Upvotes: 0
Views: 652
Reputation: 2518
if you can't use numpy
code:
import csv
x = [[ 0.0, 1.0, 2.0, 3.0 ],
[ 5.0, 1.0, 3.0, 3.0 ],
[ 1.0, 1.0, 3.0, 3.0 ]]
with open('example.csv', 'w') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(list(zip(*x)))
result:
0.0,5.0,1.0
1.0,1.0,1.0
2.0,3.0,3.0
3.0,3.0,3.0
Upvotes: 2
Reputation: 36735
You need to transpose your array first
import numpy as np
arr = np.array([[0.0, 1.0, 2.0, 3.0],[5.0, 1.0, 3.0, 3.0],[1.0, 1.0, 3.0, 3.0 ]])
arr_t = arr.T
print(arr_t)
output
[[0. 5. 1.]
[1. 1. 1.]
[2. 3. 3.]
[3. 3. 3.]]
Then follows as earlier.
Upvotes: 3