Introduction to NumPy and Matplotlib
Chapter 4: Array reshaping
Flattening an array
In this chapter, I will introduce you to different np.array
methods/functions to manipulate the shape of your np.array
s. Think of it as you giving the arrays a makeover!
I will make this practical. Over the next few pages, you will be given some missions, and you will just execute your missions! You will more likely remember them than simply reading about them!
Mission 1: Flatten all the things!
Given a multidimensional N \times K np.array
, flatten it to a single dimension (a 1D np.array
).
Check out the methods for np.array
listed on the official documentation. The answer will be right there. In fact, there are TWO methods available to solve this mission! See if you can find both!
x = np.array([[0, 1, 2, 3],
[4, 5, 6, 7],
[-6, -5, -4, -3]
])
flattened_x = ????
assert np.all(flattened_x == np.array([0, 1, 2, 3, 4, 5, 6, 7, -6, -5, -4, -3]))
Again, try this yourself first before peeking at the solutions! This is really simple!
Two methods that can be used:
flattened_x = x.flatten()
flattened_x = x.ravel()
# There is also a ravel() function, as well as the more OOP .ravel() method above
flattened_x = np.ravel(x)
# Here is yet another way! We will look at this method in more detail later.
flattened_x = x.reshape(-1)
What is the difference between .flatten()
and .ravel()
?
.flatten()
returns a copy of the elements, while .ravel()
returns a reference to the elements. So if you modify an element in an array generated by .ravel()
, you will also modify the element in the original array! Test this out yourself and compare the difference!
x = np.array([[1, 2, 3], [4, 5, 6]])
flattened_x = x.flatten()
flattened_x[0] = 10
print(flattened_x)
print(x)
x = np.array([[1, 2, 3], [4, 5, 6]])
flattened_x = x.ravel()
flattened_x[0] = 10
print(flattened_x)
print(x)