Machine Learning Prerequisites (Numpy)

23 / 32

Numpy - Mathematical Operations on NumPy Arrays - Addition and Subtraction

In this chapter, we will be discussing some mathematical operations related to NumPy arrays.

Most of the mathematical operations on NumPy arrays are element-wise operations. For example, the element at a particular index in one 2-D Numpy array gets added/subtracted/multiplied/etc. to the element at the same index in another 2- D NumPy array.

Addition

The addition of two NumPy arrays is also element-wise addition.

e.g.

import numpy as np
a = np.array([ 20, 30, 40, 50])
b = np.arange(4)

Values of b will be

array([ 0, 1, 2, 3])

c = a + b

print(c)

Output will be

array([ 20, 31, 42, 53] )

Subtraction

Subtraction between two NumPy arrays is also element-wise.

e.g.

import numpy as np
d = np.array([ 20, 30, 40, 50])
e = np.arange(4)

Values of d will be

array([ 0, 1, 2, 3])

f = d - e

print(f)

Output will be

array([ 20, 29, 38, 47] )
INSTRUCTIONS

Please follow the following steps:

(1) Import the required libraries

import numpy as np

Addition (element-wise)

(2) Please create a NumPy array a_arr with values (60, 70, 80, 90)

a_arr = np.array(<< your code comes here>>)
b_arr = np.arange(4)

Now, we have two NumPy arrays - a_arr and b_arr

(3) Add these two NumPy arrays (a_arr and b_arr), and store the result in a variable c_arr

<<your code comes here>> = a_arr  + b_arr

(4) Print array c_arr to see its values

print(c_arr)

Subtraction (element-wise)

(1) Please create a NumPy array d_arr with values (60, 70, 80, 90)

d_arr = np.array(<< your code comes here>>)
e_arr = np.arange(4)

Now, we have two NumPy arrays - d_arr and e_arr

(2) Subtract NumPy array e_arr from array d_arr, and store the result in a variable called f_arr

<<your code comes here>> = d_arr  - e_arr

(3) Print array f_arr to see its values

print(f_arr)
See Answer

No hints are availble for this assesment


Note - Having trouble with the assessment engine? Follow the steps listed here

Loading comments...