Reshape An Array
Goal¶
This post aims to describe how to reshape an array from 1D to 2D or 2D to 1D using numpy.
Reference:
Library¶
In [1]:
import numpy as np
Create a 1D and 2D array¶
In [6]:
# 1D array
arr_1d = np.array(np.arange(0, 10))
arr_1d
Out[6]:
In [7]:
arr_1d.shape
Out[7]:
In [12]:
# 2D array
arr_2d = np.array([np.arange(1, 20, 2), np.arange(100, 80, -2)]).T
arr_2d
Out[12]:
In [13]:
arr_2d.shape
Out[13]:
Reshape¶
reshape from 1D to 2D¶
In [9]:
# 1D with shape (10, ) to 2D with shape (2, 5)
np.reshape(arr_1d, [2, 5])
Out[9]:
In [18]:
np.reshape(arr_1d, [2, 5]).shape
Out[18]:
reshape from 2D to 1D¶
In [16]:
# 2D with shape (10, 2) to 2D with shape (20, )
np.reshape(arr_2d, arr_2d.size)
Out[16]:
In [17]:
np.reshape(arr_2d, arr_2d.size).shape
Out[17]:
Comments
Comments powered by Disqus