Chapter 13: NumPy in Python

This article will help you get acquainted with the widely used array-processing library in Python, NumPy.

What is NumPy?

NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays.

It is the fundamental package for scientific computing with Python.
It contains various features including these important ones:

  • 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


Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional container of generic data.
Arbitrary data-types can be defined using Numpy which allows NumPy to seamlessly and speedily integrate with a wide variety of databases.


  • Mac and Linux users can install NumPy via pip command:
pip install numpy
  • Windows does not have any package manager analogous to that in linux or mac.
    Please download the pre-built windows installer for NumPy from here (according to your system configuration and Python version).
    And then install the packages manually.

Note: All the examples discussed below will not run on an online IDE.

1. Arrays in NumPy:

NumPy’s main object is the homogeneous multidimensional array.

  • It is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers.
  • In NumPy dimensions are called axes. The number of axes is rank.
  • NumPy’s array class is called ndarray. It is also known by the alias array.

Example :

[[ 1, 2, 3],

[ 4, 2, 5]]


rank = 2 (as it is 2-dimensional or it has 2 axes)

first dimension(axis) length = 2, second dimension has length = 3

overall shape can be expressed as: (2, 3)

# Python program to demonstrate

# basic array characteristics

import numpy as np

# Creating array object

arr = np.array( [[ 1, 2, 3],

                 [ 4, 2, 5]] )

# Printing type of arr object

print("Array is of type: ", type(arr))

# Printing array dimensions (axes)

print("No. of dimensions: ", arr.ndim)

# Printing shape of array

print("Shape of array: ", arr.shape)

# Printing size (total number of elements) of array

print("Size of array: ", arr.size)

# Printing type of elements in array

print("Array stores elements of type: ", arr.dtype)

Output :

Array is of type:

No. of dimensions: 2

Shape of array: (2, 3)

Size of array: 6

Array stores elements of type: int64

2. Array creation: There are various ways to create arrays in NumPy.

  • For example, you can create an array from a regular Python list or tuple using the array function. The type of the resulting array is deduced from the type of the elements in the sequences.
  • Often, the elements of an array are originally unknown, but its size is known. Hence, NumPy offers several functions to create arrays with initial placeholder content. These minimize the necessity of growing arrays, an expensive operation.
    For example: np.zeros, np.ones, np.full, np.empty, etc.
  • To create sequences of numbers, NumPy provides a function analogous to range that returns arrays instead of lists.
  • arange: returns evenly spaced values within a given interval. step size is specified.
  • linspace: returns evenly spaced values within a given interval. num no. of elements are returned.
  • Reshaping array: We can use reshape method to reshape an array. Consider an array with shape (a1, a2, a3, …, aN). We can reshape and convert it into another array with shape (b1, b2, b3, …, bM). The only required condition is:
    a1 x a2 x a3 … x aN = b1 x b2 x b3 … x bM . (i.e original size of array remains unchanged.)
  • Flatten array: We can use flatten method to get a copy of array collapsed into one dimension. It accepts order argument. Default value is ‘C’ (for row-major order). Use ‘F’ for column major order.

Note: Type of array can be explicitly defined while creating array.

# Python program to demonstrate 
# array creation techniques 
import numpy as np  

# Creating array from list with type 
float a = np.array([[1, 2, 4], [5, 8, 7]], dtype = 'float') 
print ("Array created using passed list:\\n", a)  

# Creating array from tuple b = np.array((1 , 3, 2)) 
print ("\\nArray created using passed tuple:\\n", b)  

# Creating a 3X4 array with all zeros 
c = np.zeros((3, 4)) 
print ("\\nAn array initialized with all zeros:\\n", c)  

# Create a constant value array of complex type d = np.full((3, 3), 6, dtype = 'complex') 
print ("\nAn array initialized with all 6s." "Array type is complex:\n", d)  

# Create an array with random values 
e = np.random.random((2, 2))
print ("\\nA random array:\\n", e)

# Create a sequence of integers
# from 0 to 30 with steps of 5 
f = np.arange(0, 30, 5) 
print ("\\nA sequential array with steps of 5:\\n", f)

# Create a sequence of 10 values in range 0 to 5
g = np.linspace(0, 5, 10)
print ("\nA sequential array with 10 values between" "0 and 5:\\n", g)  

# Reshaping 3X4 array to 2X2X3 array 
arr = np.array([[1, 2, 3, 4], [5, 2, 4, 2], [1, 2, 0, 1]])
newarr = arr.reshape(2, 2, 3)
print ("\\nOriginal array:\\n", arr) 
print ("Reshaped array:\\n", newarr)

# Flatten array 
arr = np.array([[1, 2, 3], [4, 5, 6]]) 
flarr = arr.flatten()  print ("\\nOriginal array:\\n", arr) 
print ("Fattened array:\\n", flarr)

3. Array Indexing:

Knowing the basics of array indexing is important for analysing and manipulating the array object. NumPy offers many ways to do array indexing.

  • Slicing: Just like lists in python, NumPy arrays can be sliced. As arrays can be multidimensional, you need to specify a slice for each dimension of the array.
  • Integer array indexing: In this method, lists are passed for indexing for each dimension. One to one mapping of corresponding elements is done to construct a new arbitrary array.
  • Boolean array indexing: This method is used when we want to pick elements from array which satisfy some condition.

4. Basic operations:

Plethora of built-in arithmetic functions are provided in NumPy.

  • Operations on single array: We can use overloaded arithmetic operators to do element-wise operation on array to create a new array. In case of +=, -=, *= operators, the existing array is modified.

Unary operators: Many unary operations are provided as a method of ndarray class. This includes sum, min, max, etc. These functions can also be applied row-wise or column-wise by setting an axis parameter.

Binary operators: These operations apply on array elementwise and a new array is created. You can use all basic arithmetic operators like +, -, /, , etc. In case of +=, -=, = operators, the exsisting array is modified.

  • Universal functions (ufunc): NumPy provides familiar mathematical functions such as sin, cos, exp, etc. These functions also operate elementwise on an array, producing an array as output.

Note: All the operations we did above using overloaded operators can be done using ufuncs like np.add, np.subtract, np.multiply, np.divide, np.sum, etc.



Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?