Numpy Basics — 1

Devil’s Advocate
3 min readFeb 13, 2023

--

NumPy is a popular library for numerical computing in Python. Let’s look at two of the common array methods used in NumPy and simple examples to demonstrate their usage.

array.shape: returns the shape of an array as a tuple.

import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.shape)
# Output: (2, 3)

Here, the shape is expressed in terms of the number of rows and the number of columns (in 2 dimensions).

array.reshape: returns an array with a new shape, without changing the original array.

import numpy as np
a = np.array([1, 2, 3, 4, 5, 6])
b = a.reshape((2, 3))
print(b)
# Output:
# [[1 2 3]
# [4 5 6]]

array.reshape is a method that is used to change the shape of a NumPy array. It takes as an argument the desired shape of the new array and returns a new array with the specified shape. The size of the new array must match the size of the original array.

If the sizes of the original array and the new shape are not directly compatible, NumPy raises a ValueError. For example, consider the following code:

import numpy as np
a = np.array([1, 2, 3, 4, 5, 6])
b = a.reshape(2, 3)
print(b)
# Output:
# [[1 2 3]
# [4 5 6]]

In this example, the original array has a size of 6, and the new shape is (2, 3). The size of the new array is 2 * 3 = 6, which is equal to the size of the original array, so the reshape operation is successful.

array.reshape works for two-dimensional arrays as well. In fact, it can be used to reshape arrays of any number of dimensions. The important thing to keep in mind is that the size of the new array must match the size of the original array.

Here’s an example of using array.reshape with a two-dimensional array:

import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
b = a.reshape(3, 2)
print(b)
# Output:
# [[1 2]
# [3 4]
# [5 6]]

In this example, the original array a has a shape of (2, 3), and we are reshaping it to a shape of (3, 2). The size of the new array b is 3 * 2 = 6, which is equal to the size of the original array a, so the reshape operation is successful.

However, if we try to reshape the original array to a shape that has a different size, a ValueError is raised.

import numpy as np
a = np.array([1, 2, 3, 4, 5, 6])
try:
b = a.reshape(3, 3)
except ValueError as e:
print("Caught ValueError:", e)
# Output: Caught ValueError: cannot reshape array of size 6 into shape (3,3)

In this example, the original array has a size of 6, and we are trying to reshape it to a shape of (3, 3), which has a size of 3 * 3 = 9, which is not equal to the size of the original array. As a result, a ValueError is raised.

We will see more of these nuances in our next post …

--

--

Devil’s Advocate

Seeker for life. Looking to make technology simpler for everyone.