Created
February 15, 2016 06:54
-
-
Save aravindhebbali/0ae76fcfcd8279bd4277 to your computer and use it in GitHub Desktop.
NumPy for Beginners: Reshaping NumPy Arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
# one dimensional array | |
np1 = np.arange(0, 12) | |
np1 | |
# reshape() method | |
# modify to 3 x 4 two dimensional array | |
np1.reshape(3, 4) | |
# np1 is still a one dimensional array | |
np1 | |
# reshape can be used to reduce the dimensions as well | |
# two dimensional array | |
np2 = np.array([[1, 2, 3], [4, 5, 6]]) | |
# use reshape to make it one dimensional | |
np2.reshape(6) | |
# resize() method | |
# original array | |
np1 | |
# modify the dimension using the resize() method | |
np1.resize(3, 4) | |
np1 | |
# retrieve the dimension of an array using shape() method | |
np1.shape | |
# modify the dimension of the array | |
np1.shape = (4, 3) | |
np1 | |
# the ravel method | |
np1.ravel() | |
# the flatten method | |
np1.flatten() | |
# the dimension of np1 is not modified | |
np1 | |
# difference between reshape(), ravel() and flatten() | |
np1 | |
# create 3 new arrays | |
np_reshape = np1.reshape(3, 4) | |
np_ravel = np1.ravel() | |
np_flatten = np1.flatten() | |
# np1 is not modified | |
np1 | |
# make changes to np_reshape | |
# set the element in the third row/column to 25 | |
np_reshape[2, 2] = 25 | |
# test if the change is reflected in np1 | |
np1 | |
# test if the change is reflected in np_ravel | |
np_ravel | |
# test if the change is reflected in np_flatten | |
np_flatten | |
# transpose method() | |
np1.transpose() | |
# T property | |
np1.T |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment