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]:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [7]:
arr_1d.shape
Out[7]:
(10,)
In [12]:
# 2D array
arr_2d = np.array([np.arange(1, 20, 2), np.arange(100, 80, -2)]).T
arr_2d
Out[12]:
array([[  1, 100],
       [  3,  98],
       [  5,  96],
       [  7,  94],
       [  9,  92],
       [ 11,  90],
       [ 13,  88],
       [ 15,  86],
       [ 17,  84],
       [ 19,  82]])
In [13]:
arr_2d.shape
Out[13]:
(10, 2)

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]:
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
In [18]:
np.reshape(arr_1d, [2, 5]).shape
Out[18]:
(2, 5)

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]:
array([  1, 100,   3,  98,   5,  96,   7,  94,   9,  92,  11,  90,  13,
        88,  15,  86,  17,  84,  19,  82])
In [17]:
np.reshape(arr_2d, arr_2d.size).shape
Out[17]:
(20,)

Comments

Comments powered by Disqus