All NumPy operations are vectorized, where you apply operations to the whole array instead of on each element individually. This is not just neat and handy but also improves the performance of computation compared to using loops. In this section, we will experience the power of NumPy vectorized operations. A key idea worth keeping in mind before we start exploring this subject is to always think of entire sets of arrays instead of each element; this will help you enjoy learning about NumPy Arrays and their performance. Let's start by doing some simple calculations with scalars and between NumPy Arrays:
In [1]: import numpy as np In [2]: x = np.array([1, 2, 3, 4]) In [3]: x + 1 Out[3]: array([2, 3, 4, 5])
All the elements in the array are added by 1
simultaneously. This is very different from Python or most other programming languages. The elements in a NumPy Array all have the same dtype
; in the preceding example, this is numpy.int
(this is either...