0

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)
1
  • Transpose the matrix before writing it out Commented Jun 22, 2021 at 8:32

2 Answers 2

3

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.

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

Comments

2

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

1 Comment

Thanks @leaf_yakitori, both the answers helped!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.