Introduction to NumPy and Matplotlib
Chapter 2: NumPy arrays
NumPy arrays
The main star of NumPy
is the np.ndarray
object. It stands for N-dimensional arrays. You can also use the shorter np.array
as an alias (we will use this for our lesson!)
NumPy
is all about representing your vectors/matrices as np.array
instances, and using the operators and methods of the object to transform array instances. That’s it really!
The key knowledge you need to figure out is what operators, attributes and methods are available for a np.array
instance, and how to use them! And also all the many functions provided by NumPy
to help you manipulate the np.array
s.
np.array
versus list
Why do we need np.array
s when we have Python list
s?
Well, np.array
s are more efficient, and these often have smaller memory consumption and better runtime compared to Python list
s. So definitely use np.ndarray
over list
any time for large scale array/matrix operations.
You should also treat np.array
as something completely different from Python list
s. How you use np.array
instances will be quite different from list
s! So don’t start using list
methods with np.array
s - it will probably not work!
You can create a new np.array
instance by passing in a list
(or any other sequence) as an argument to the constructor.
Conversely, use the .tolist()
method of np.array
to convert the NumPy array to a list
.
>>> x = np.array([[1, 2, 3], [4, 5, 6]])
>>> print(x)
[[1 2 3]
[4 5 6]]
>>> print(type(x))
<class 'numpy.ndarray'>
>>> x_list = x.tolist()
>>> print(x_list)
[[1, 2, 3], [4, 5, 6]]
>>> print(type(x_list))
<class 'list'>