Simple Operations
Lesson 16 of 18 in Coddy's Numpy Fundamentals course.
Arithmetic operations in Numpy arrays have great flexibility
Example 1
Adding, subtracting, dividing, and multiplying between numbers and arrays
ary = np.array([0, 5, 10, 15, 20])
ary + 5 # --> [ 5, 10, 15, 20, 25]
ary - 5 # --> [-5, 0, 5, 10, 15]
ary / 5 # --> [ 0, 1, 2, 3, 4]
ary * 5 # --> [ 0, 25, 50, 75, 100]Example 2
Operations with a 2D array
ary = np.array([[0, 1], [2, 3], [4, 5]])
ary + 5
>>> [[5, 6], [7, 8], [9, 10]]Example 3
Arithmetic operations between arrays
Adding elements by their matching position
ary1 = np.array([1, 2, 3])
ary2 = np.array([4, 5, 6])
ary1 + ary2 # [1 + 4, 2 + 5, 3 + 6]
>>>[5, 7, 9] Example 4
Arithmetic operations between 2D arrays
ary1 = np.array([[0, 1], [2, 3], [3, 4], [5, 6]])
ary2 = np.array([[0, 1], [2, 3], [3, 4], [5, 6]])
ary1 + ary2 # --> [[0+0, 1+1], [2+2, 3+3], [3+3, 4+4], [5+5, 6+6]]
>>> [[ 0, 2], [ 4, 6], [ 6, 8], [10, 12]]
ary1 = np.array([[0, 1], [2, 3], [3, 4], [5, 6]])
ary2 = np.array([[2, 5]])
ary1 + ary2 # --> [[0+2, 1+5], [2+2, 3+5], [3+2, 4+5], [5+2, 6+5]]
>>> [[2, 6], [4, 8], [5, 9], [7, 11]]Note: Operations between arrays without matching shapes will fail!
ary1 = np.array([[0, 1], [2, 3], [3, 4], [5, 6]])
ary2 = np.array([[2, 5, 3]])
ary1 + ary2
>>> ValueError: operands could not be broadcast together with shapes (4,2) (1,3) This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate a function called func_operation the receives three python lists
and returns the sum of ary1 * ary2 / ary3
Round the result to two decimal places after the dot.
- To round the result use the
roundmethod:round(num, 2)
Try it yourself
import numpy as np
def func_operation(lst1, lst2, lst3):
# Complete here
All lessons in Numpy Fundamentals
2N-Dimensional Array Creation
Higher DimensionUnderstanding ShapesPopulate with Fixed ValuesNumpy TypesRangeReshape