Jovian
⭐️
Sign In

NumPy

Numpy, Numerical Python, is a powerful and supercharged library in python for handling multidimensional array objects. It offers tools for working with these arrays. Numpy can perform mathematical as well as logical operation on arrays, shape manipulation using fourier transforms and routines and it also has built in functions for random number generation and linear algebra.

Installing NumPy

Python distribution doesn't come with NumPy package. The best way to install numpy is to use pip command,

pip install numpy

To check whether the NumPy package is installed properly in your machine, try to import it from the Python prompt. We have used "as" keyword here to alias NumPy package with the name "np".

In [1]:
import numpy as np

An error message will be prompted if it is not installed properly.

Why NumPy?

Why we want to go for NumPy arrays? Why we can't simply use Python List for these numerical computations? There are some benefits when using NumPy instead of List.

  • NumPy arrays consumes less memory compared to List.
  • It is faster for performing scientific computing problems.
  • It is easy to use.

Lets see one example program to prove that NumPy arrays consumes less memory compared to List

In [10]:
# Importing the required packages.
import sys
import time
import numpy as np

# NumPy array with 1000 elements
numpy_array = np.arange(1000)

# Python List with 1000 elements (0 to 999)
list = range(0, 1000)

# Size of NumPy array and Python List
print("Size of numpy_array: \n", numpy_array.itemsize * numpy_array.itemsize)
print("Size of list: \n", sys.getsizeof(1)*len(list))
Size of numpy_array: 16 Size of list: 28000

NumPy Arrays

NumPy array is the central data structure of the NumPy library. It is an N-dimensional array type called ndarray. Let's now jump into the specialities of NumPy arrays.

Creating NumPy Arrays

To create a NumPy array, np.array() function can be used, All you need to do is pass a list to it, and optionally, you can also specify the data type of the data.

In [9]:
import numpy as np

list = [24, 10, 2019]

# np.array object converts list into NumpPy array
numpy_array1 = np.array(list)
print("List converted into a numpy array : \n", numpy_array1)

# Above operation can be combined without declaring list
numpy_array2 = np.array([17, 11, 1999])
print("A numpy array without declaring list : \n", numpy_array2)

# NumPy array with more than one dimension
numpy_array3 = np.array([[24, 10, 2019], [17, 11, 1999]])
print("A numpy array with more than one dimension : \n", numpy_array3)

# NumPy array with datatype as complex
numpy_array4 = np.array([2, 4, 1], dtype = complex)
print("A numpy array of complex datatype : \n", numpy_array4)
List converted into a numpy array : [ 24 10 2019] A numpy array without declaring list : [ 17 11 1999] A numpy array with more than one dimension : [[ 24 10 2019] [ 17 11 1999]] A numpy array of complex datatype : [2.+0.j 4.+0.j 1.+0.j]

There are also certain set of functions for creating NumPy arrays,

In [12]:
import numpy as np

# A 2x2 NumPy array with all zeros
numpy_array5 = np.zeros((2, 2))
print("A numpy array with all zeros : \n", numpy_array5)

# A 2x2 NumPy array with random values 
numpy_array6 = np.random.random((2, 2))
print("A numpy array with random values : \n", numpy_array6)
A numpy array with all zeros : [[0. 0.] [0. 0.]] A numpy array with random values : [[0.06332328 0.19111232] [0.51840569 0.72245051]]

NumPy Array Datatypes and Attributes

Every N-dimensional array in NumPy has an associated data type object and is a grid of elements of the same type. This data type object is denoted as "dtype". The underlying information of data type object is,

  • Number of bytes or size of the data.
  • Type of the data (integer, float etc.)
  • Byte order of the data.
  • In case of structured type, the names of fields, data type of each field and part of the memory block taken by each field.
  • If data type is a subarray, its shape and data type.

Whenever a data-type is required in a NumPy function or method, either a dtype object or something that can be converted to one can be supplied. Such conversions are done by the dtype constructor.

np.dtype(object, align, copy)

The parameters are :

  • Object - To be converted to data type object.
  • Align - If true, adds padding to the field to make it similar to C-struct.
  • Copy - Makes a new copy of dtype object. If false, the result is reference to builtin data type object.

Let's see some examples,

In [19]:
import numpy as np

# A NumPy array of the type integer (int32)
numpy_array7 = np.array([24, 10])
print("Data type of the numpy array ",numpy_array7, "\n", numpy_array7.dtype)

# A NumPy array of the type float (float64)
numpy_array8 = np.array([24.10, 10.10])
print("Data type of the numpy array ",numpy_array8, "\n", numpy_array8.dtype)

# A NumPy array of the type complex (complex128)
numpy_array9 = np.array([1 + 2j, 3 + 5j])
print("Data type of the numpy array ",numpy_array9, "\n", numpy_array9.dtype)
Data type of the numpy array [24 10] int32 Data type of the numpy array [24.1 10.1] float64 Data type of the numpy array [1.+2.j 3.+5.j] complex128

Now we can list out the various attributes of NumPy arrays.

  • ndarray.shape - Returns the shape of NumPy arrays in a tuple consisting of array dimensions. It can also be used to resize the array.
In [25]:
import numpy as np

# Single dimension NumPy array of the size, 3
numpy_array10 = np.array([21, 11, 2019])
print("Size/Shape of single dimension numpy array, ", numpy_array10, "\n", numpy_array10.shape)

# 3x3 dimensional NumPy array
numpy_array11 = np.array([[21, 11, 2019], [22, 11, 2019], [23, 11, 2019]])
print("Size/Shape of the 3x3 dimensional numpy array, \n", numpy_array11, "\n", numpy_array11.shape)

# 2x3 dimensional NumPy array
numpy_array12 = np.array([[21, 11, 2019], [22, 11, 2019]])
print(numpy_array12.shape, " dimensional numpy array before resizing \n", numpy_array12)
# Resizing 2x3 dimensional array into a 3x2 dimensional array
numpy_array12.shape = (3, 2)
print("Size/Shape of the numpy array after resizing it \n", numpy_array12.shape)
print("Numpy array after resizing it into 3x2 dimension \n", numpy_array12)
Size/Shape of single dimension numpy array, [ 21 11 2019] (3,) Size/Shape of the 3x3 dimensional numpy array, [[ 21 11 2019] [ 22 11 2019] [ 23 11 2019]] (3, 3) (2, 3) dimensional numpy array before resizing [[ 21 11 2019] [ 22 11 2019]] Size/Shape of the numpy array after resizing it (3, 2) Numpy array after resizing it into 3x2 dimension [[ 21 11] [2019 22] [ 11 2019]]
  • ndarray.ndim - The "ndim" attribute returns the dimension of a NumPy array.
In [33]:
import numpy as np

numpy_array13 = np.array([[10, 11], [12, 13]])
# numpy_array13.ndim returns dimension for the numpy array, numpy_array13
print("A numpy array \n", numpy_array13, "\nwith its dimension as \n", numpy_array13.ndim)
A numpy array [[10 11] [12 13]] with its dimension as 2
  • numpy.itemsize - This array attribute returns the length of each element of array in bytes.
In [35]:
import numpy as np

# Second argument which is dtype which means the items datatype, and it is int8. 
# That means the bytes of each character is 1.
numpy_array14 = np.array([24, 10, 2019], dtype = np.int8)
print(numpy_array14.itemsize)
1
In [37]:
# Numpy array of data type float32
numpy_array15 = np.array([24, 10, 2019], dtype = np.float32) 
print(numpy_array15.itemsize)
4

Initialising Different NumPy Arrays

A NumPy array can be initialised in several ways,

  • numpy.empty - It creates an uninitialized array of specified shape and dtype. The elements in an array show random values as they are not initialized.

We have already covered functions "np.zeros" and "np.random.random" in the array creation section.

In [38]:
import numpy as np

# Generates a 2x2 dimensional numpy array with random values
numpy_array16 = np.empty([2, 2], dtype = int)
print(numpy_array16)
[[10 11] [12 13]]
  • numpy.ones - Returns a new array of specified size and type, filled with ones.
In [39]:
import numpy as np 

# Generates a 2x2 dimensional array filled with ones
numpy_array17 = np.ones([2,2], dtype = int) 
print(numpy_array17)
[[1 1] [1 1]]
  • numpy.arange - Returns an ndarray object containing evenly spaced values within a given range. Syntax as "numpy.arange(start, stop, step, dtype)"
In [40]:
import numpy as np

# A numpy array starting from 0 to 9
numpy_array18 = np.arange(10)
print("A numpy array with range 5 \n", numpy_array18)

# A numpy array starting from 1 to 10 (excluding 10) with 2 as spacing between values
numpy_array19 = np.arange(1, 10, 2)
print("A numpy array with start, stop and step parameters \n", numpy_array19)
A numpy array with range 5 [0 1 2 3 4 5 6 7 8 9] A numpy array with start, stop and step parameters [1 3 5 7 9]

Data Manipulation using NumPy Arrays (Indexing and Slicing)

In [ ]:
 

Mathematical Operations in NumPy Arrays

Statistical Functions in NumPy

Linear Algebra in NumPy

Array Broadcasting

Image Operations in NumPy

In [ ]:
import jovian
jovian.commit()
[jovian] Saving notebook..
In [ ]: