Python – Numpy Arrays

What is Numpy?

Numpy is a module that is available in python for scientific analysis projects. It also provides a high-performance multidimension array object, and tools for working with these arrays.

#To check which version of Numpy you are using: 
import numpy 
#This code will print a single dimensional array.

import numpy as np

a = np.array([1,2,3])

#This will print a multidimensional array

import numpy as np

a = np.array([ [1,2,3], [4,5,6] ]) 


Why is Numpy better than list?

We use Numpy because it uses less memory, it is fast, and it can be executed in less steps than list.

For example to show that numpy uses less memory…

import numpy as np

import time

import sys

#takes integer values from 0 to 1000 and store in variable s

s = range(1000)


#arrange function is similar to the range

d = np.arange(1000)

#get the size of the numpy array


You will see that the numpy array has a size of 4000 versus 14000 in the standard list

Another example to show the time it takes less time and can be executed in less steps compared to the list.

import numpy as np
import time
import sys

SIZE = 1000000

#define two lists. 
L1 = range(SIZE)
L2 = range(SIZE)

#define two numpy arrays
A1 = np.arange(SIZE)
A2 = np.arange(SIZE)

#this will calculate the sum in lists

start = time.time()
result = [(x,y) for x,y in zip(L1,L2)]

print((time.time() - start) * 1000)

#for numpy all you need to do is add the two array variables together to sum lists

start = time.time()

result = A1 + A2

print((time.time() - start) * 1000)

The result is that the list took more time than the numpy array.

So, you can find the number of dimensions in the array, the number of bytes in the array, and the variable type in the array. Additionally you can also find the size of the array and shape of the array which is the number of columns and number of rows

import numpy as np

a = np.array([[1,2,3], [2,3,4]])

#prints the number of dimensions in the array

#prints the number of bytes in the array

#prints the data type in the array

#prints the size of the array

#prints the shape of the array

Some examples of mathematical operations

import numpy as np

#create numpy array
a = np.array([[1,2,3,4]])

#find max value

#find min value

#find median value
#print sum

Some more advanced mathematics

import numpy as np

a = np.array([[1,2,3,4]])

#find square root of each element in array

#find standard devaiation of each element in the array
#the standard deviation is the variation from the mean of the array

Also, some matrix mathematics

import numpy as np

a = np.array([[1,2,3],[3,4,5]])
b = np.array([[1,2,3],[3,4,5]])

#matrix addition

#matrix subtraction

#matrix multiplication

#matrix division


**This article is written for Python 3.6

<< Numpy Basics 

Numpy Dot Product >> 

%d bloggers like this: