Shape Reshape

import numpy as np
a = np.arange(12)
print(a)
[ 0  1  2  3  4  5  6  7  8  9 10 11]
a.ndim
1

Shape

a.shape = (4, 3)
print(a)
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]
a.ndim # as the shape changed, it will not print 1
2

Reshape

b = a.reshape(6, 2)
print(b)
[[ 0  1]
 [ 2  3]
 [ 4  5]
 [ 6  7]
 [ 8  9]
 [10 11]]

Shape vs Reshape

numpy.reshape will copy the data if it can’t make a proper view, whereas setting the shape will raise an error instead of copying the data.

It is not always possible to change the shape of an array without copying the data.

If you want an error to be raise if the data is copied, you should assign the new shape to the shape attribute of the array.

(SOF)

c = np.arange(12).reshape(2, 3, 2)
print(c)
[[[ 0  1]
  [ 2  3]
  [ 4  5]]

 [[ 6  7]
  [ 8  9]
  [10 11]]]
c.shape
(2, 3, 2)
c.ndim
3
d = c.reshape(4, 3)
print(d)
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]
d.shape
(4, 3)
d.ndim
2

Swap Axes

e = c.reshape(4, 3).swapaxes(0, 1)
print(e)
[[ 0  3  6  9]
 [ 1  4  7 10]
 [ 2  5  8 11]]
e.shape
(3, 4)
e.ndim
2