10 Basic Arithmetic Operations with NumPy array

NumPy is the fundamental package for scientific computing with Python. It contains among other things: a powerful N-dimensional array object sophisticated (broadcasting) functions tools for integrating C/C++ and Fortran code useful linear algebra, Fourier transform, and random number capabilities
Basic Aritmetic Operations with NumPy
Basic Aritmetic Operations with NumPy

NumPy is one of most fundamental Python packages for doing any scientific computing in Python. NumPy’s N-dimenisonal array structure offers fantastic tools to numerical computing with Python.

Let us see 10 most basic arithmetic operations with NumPy that will help greatly with Data Science skills in Python.

Let us first load the NumPy library

# import NumPy
import numpy as np

Let us create two NumPy arrays using NumPy’s random module. We will use random.seed to reproduce the same random numbers in the two arrays.

# set seed for random numbers
np.random.seed(42)
# create arrays using NumPy's random module
a = np.random.randint(1,3,5)
b = np.random.randint(0,10,5)

We have two numpy arrays a and b and we will use them in our examples below.

>print(a) 
[1 2 1 1 1]
>print(b)
[7 4 6 9 2]

1. How to subtract two arrays?

np.subtract(b,a)
array([-2,  2,  2, -2,  3])

2. How to add two arrays?

np.add(b,a)
array([16,  6, 14, 12, 11])

3. How to divide two arrays?

np.divide(a,b)
array([0.14285714, 0.5, 0.16666667, 0.11111111, 0.5])

4. How to multiply two arrays?

np.multiply(a,b)
array([7, 8, 6, 9, 2])

5. How To Compute Exponent of an array?

np.exp(a)
array([2.71828183, 7.3890561 , 2.71828183, 2.71828183, 2.71828183])

6. How to Compute Square Root of an array?

np.sqrt(a)
array([2., 4., 2., 2., 2.])

7. How to Compute Sine/Cosine?

np.sin(a)
array([0.84147098, 0.90929743, 0.84147098, 0.84147098, 0.84147098])

8. How to Take Logarithm?

np.log(a)  
array([0., 0.69314718, 0., 0., 0.])
np.log2(a)  
array([0., 1., 0., 0., 0.])

9. How to Take Dot Product?

a.dot(b)
32

10. How to Round an Array?

np.random.seed(42)
a = np.random.rand(5)
print(a)
[0.37454012 0.95071431 0.73199394 0.59865848 0.15601864]
np.around(a)
array([0., 1., 1., 1., 0.])