Contenido del Curso
Ultimate NumPy
3. Commonly used NumPy Functions
Ultimate NumPy
Basic Mathematical Operations
Now that you're familiar with the concept of broadcasting, let’s discuss some basic mathematical operations in NumPy.
Scalar Operations
Remember, broadcasting allows you to perform mathematical operations between two arrays of compatible shapes or between an array and a scalar.
Let’s first look at an example with scalars:
As you can see, each operation is performed element-wise on the array. Essentially, a scalar is broadcast to an array of the same shape as our original array
, where all the elements are the same number. Therefore, the operation is performed on every pair of corresponding elements of the two arrays.
Operations Between Two Arrays
If the shapes of two arrays are compatible, broadcasting is performed if needed, and once again, an operation is performed element-wise:
Division, subtraction, and other arithmetic operations work in a similar fashion. Here is an example where the second array is broadcast:
arr_2
is broadcast to a 2D array with two identical rows, each containing the array [5, 6, 7]
.
Tarea
Calculate the quarterly revenue growth for each product in percent (each row of a 2D array contains quarterly sales for a certain product).
¿Todo estuvo claro?
Contenido del Curso
Ultimate NumPy
3. Commonly used NumPy Functions
Ultimate NumPy
Basic Mathematical Operations
Now that you're familiar with the concept of broadcasting, let’s discuss some basic mathematical operations in NumPy.
Scalar Operations
Remember, broadcasting allows you to perform mathematical operations between two arrays of compatible shapes or between an array and a scalar.
Let’s first look at an example with scalars:
As you can see, each operation is performed element-wise on the array. Essentially, a scalar is broadcast to an array of the same shape as our original array
, where all the elements are the same number. Therefore, the operation is performed on every pair of corresponding elements of the two arrays.
Operations Between Two Arrays
If the shapes of two arrays are compatible, broadcasting is performed if needed, and once again, an operation is performed element-wise:
Division, subtraction, and other arithmetic operations work in a similar fashion. Here is an example where the second array is broadcast:
arr_2
is broadcast to a 2D array with two identical rows, each containing the array [5, 6, 7]
.
Tarea
Calculate the quarterly revenue growth for each product in percent (each row of a 2D array contains quarterly sales for a certain product).
¿Todo estuvo claro?