Introduction
In this lab, you will learn the NumPy shape manipulation functions that allow you to manipulate the shape of NumPy arrays.
Achievements
- Reshaping arrays
- Concatenating and splitting arrays
- Transposing arrays
In this lab, you will learn the NumPy shape manipulation functions that allow you to manipulate the shape of NumPy arrays.
The reshape
function allows you to change the shape of a NumPy array. The syntax of the reshape
function is as follows:
np.reshape(a, new_shape)
a
is the input array and new_shape
is the desired new shape of the array.Open the Python shell by typing the following command in the terminal.
python3
NumPy is already installed, you can import it in your Python code:
import numpy as np
Create an array a
of shape (2, 3) as an example:
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.shape)
Output:
(2, 3)
You can reshape this array to a shape of (3, 2) using the reshape
function:
b = np.reshape(a, (3, 2))
print(b.shape)
print(b)
Output:
(3, 2)
[[1 2]
[3 4]
[5 6]]
NumPy provides two functions for concatenating arrays:
You can split arrays using the np.split
function.
Create two arrays a
and b
as an example:
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
You can concatenate these arrays along the first axis(0) using the np.concatenate
function:
c = np.concatenate((a, b))
print(c)
Output:
[1 2 3 4 5 6]
You can also concatenate these arrays along a new axis using the np.stack
function:
d = np.stack((a, b))
print(d)
print(d.shape)
Output:
[[1 2 3]
[4 5 6]]
(2, 3)
Create an array a
of shape (6,) as an example:
a = np.array([1, 2, 3, 4, 5, 6])
You can split this array into two arrays of length 3 using the np.split
function:
b, c = np.split(a, 2)
print(b)
print(c)
Output:
[1 2 3]
[4 5 6]
The transpose
function allows you to transpose the axes of a NumPy array. The syntax of the transpose
function is as follows:
a.transpose([axis1, axis2, ...])
axis1
, axis2
, etc. are the axes to be transposed.create an array a
of shape (2, 3) as an example:
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a)
print(a.shape)
Output:
[[1 2 3]
[4 5 6]]
(2, 3)
You can transpose this array using the transpose
function:
b = a.transpose()
print(b)
print(b.shape)
Output:
[[1 4]
[2 5]
[3 6]]
(3, 2)
You can also transpose specific axes of the array. For example, you can transpose the axes of the array a
to have a shape of (3, 2) using the following code:
c = a.transpose(1, 0)
print(c)
print(c.shape)
Output:
[[1 4]
[2 5]
[3 6]]
(3, 2)
Congratulations! You have completed the NumPy Shape Manipulation Lab.
In this lab, you learned the NumPy shape manipulation functions reshape
, concatenate
, stack
, split
, and transpose
. These functions allow you to manipulate the shape of NumPy arrays and are essential for many data manipulation tasks.