3

I have a numpy array that has shape of (16,2)

[[-109.12722222    1454.        ]
 [-109.12694444    1459.        ]
 [-109.12666667    1463.        ]
 [-109.12638889    1465.        ]
 [-109.12611111    1464.        ]
 [-109.12583333    1464.        ]
 [-109.12555556    1464.        ]
 [-109.12527778    1464.        ]
 [-109.125         1464.        ]
 [-109.12472222    1465.        ]
 [-109.12444444    1465.        ]
 [-109.12416667    1463.        ]
 [-109.12388889    1462.        ]
 [-109.12361111    1461.        ]
 [-109.12333333    1459.        ]
 [-109.12305556    1454.        ]]

and I want to know how to reshape it so it is (4,4,2).

[[-109.12722222    1454.        ] [-109.12694444    1459.        ][-109.12666667    1463.        ][-109.12638889    1465.        ]
 [-109.12611111    1464.        ] [-109.12583333    1464.        ] [-109.12555556    1464.        ][-109.12527778    1464.        ]
 [-109.125         1464.        ][-109.12472222    1465.        ][-109.12444444    1465.        ][-109.12416667    1463.        ]
 [-109.12388889    1462.        ][-109.12361111    1461.        ][-109.12333333    1459.        ][-109.12305556    1454.        ]]

I tried this:

numpy_array = np.reshape(4, 4, 2)

but it throws:

ValueError: cannot reshape array of size 1 into shape (4,)

6
  • 1
    Where's the array that you are trying to reshape? Commented Aug 23, 2019 at 5:48
  • how can you convert 2 dimensional array to three dimensional? Commented Aug 23, 2019 at 5:49
  • @Kishan there were people who did it here, but when I did that it still threw the same error stackoverflow.com/questions/7372316/… Commented Aug 23, 2019 at 5:55
  • You code does not match any of these examples in that link. Commented Aug 23, 2019 at 5:57
  • 1
    Did you read the documentation on how to use numpy.reshape - docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html? Commented Aug 23, 2019 at 6:02

1 Answer 1

3

You can make use of numpy.newaxis

import numpy as np

a = np.zeros((16, 2))
b = a[:, :, np.newaxis]
c = b.reshape(4, 4, 2)

print(c.shape)
Sign up to request clarification or add additional context in comments.

2 Comments

Got it! I realized what I was forgetting, thanks for the answer.
a.reshape(4,4,2) or np.reshape(a, (4,4,2)) would work just as well. You don't need the newaxis step.

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.