## Changing numpy array column or shape

Changing the order of columns. This is useful when you want to reorder image data, e.g., rgb -> bgr.

```In [14]: x = np.arange(10)

In [15]: x
Out[15]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [16]: np.resize(x, (5, 2))
Out[16]:
array([[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]])

In [17]: np.resize(x, (5, 2))[:, ::-1]
Out[17]:
array([[1, 0],
[3, 2],
[5, 4],
[7, 6],
[9, 8]])
```

Changing the order of axis. For image, this is useful if you want to change the channel axis to the arbitrary position. As an example, matplotlib.pyplt.plot() accepts images in the form of (x, y, channel). Your data might be in the form of (channel, x, y).

```# 256x256 image. Channel (or rgb) is at the front.
In [26]: x = np.ones((3, 256, 256))

In [27]: x.shape
Out[27]: (3, 256, 256)

# Move the channel axis to the last.
In [29]: np.rollaxis(x, 0, 3).shape
Out[29]: (256, 256, 3)
```

np.transpose can be used to change the order of axis.

```In [25]: x = np.ones((1, 2, 3))
In [26]: x.shape
Out[26]: (1, 2, 3)
In [28]: x.transpose((2, 0, 1)).shape
Out[28]: (3, 1, 2)
```

Similar Posts: