Skip to Main Content
It looks like you're using Internet Explorer 11 or older. This website works best with modern browsers such as the latest versions of Chrome, Firefox, Safari, and Edge. If you continue with this browser, you may see unexpected results.

Python for Basic Data Analysis: NP.6 Math with NumPy I

Get started on your learning journey towards data science using Python. Equip yourself with practical skills in Python programming for the purpose of basic data manipulation and analysis.

Math functions with NumPy

More often than not, data analysis will involve some form of mathematical calculations. Having a large data set also means that you would not want to have to manually count each data point. What you can do is to perform mathematical calculations using arrays.

Basic mathematical functions on arrays are element wise operators. Let's take a look at what this means.


Let's start by creating some arrays to work with:

Math with NumPy I

Addition

There are 2 ways to perform element-wise addition with arrays.

Method 1: Simply just add them together using + operator

print(x + y)


Method 2: Use np.add

print(np.add(x,y))

Subtraction, Multiplication & Division

Similarly, to subtract use np.subtract or -, to multiply use np.multiply or *, and to divide use np.divide or /.
 

Square root

To perform element-wise square root we can use np.sqrt

Syntax

print(np.sqrt(x+y))


Matrix Multiplication

To look for the inner product, or matrix multiplication of arrays, use np.dot.

We have to first make sure that the rows and columns match, just like we would for any other matrix multiplication.
 

Sum


Sum all elements in array

To sum up elements in an array, use np.sum


Syntax

(np.sum(array))



Sum of each column

To find the sum of each column (adding up all row values for each column) we just need to specify the axis = 0 
 

Syntax

print(np.sum(x, axis=0))



Sum of each row

To find the sum of each row we use axis = 1


Syntax

print(np.sum(x, axis=1))

 

Exercises

Use this array for the following practice: 

myArray = np.arange(10)


1. Find the square of every number in array

2. Find the square root of every number in array

3. Multiply the square of each number in array with its respective square root

Video Guide

Further Readings