Why Should We Use NumPy?

Why Should We Use NumPy?

Understanding NumPy Features Before Re-Inventing The Wheel

NumPy is one of the most powerful Python libraries. This article will outline the core features of the NumPy library. It will also provide an overview of the common mathematical functions in an easy-to-follow manner.

If you want to understand everything about Python programming language

What is NumPy?

  • NumPy is an open source numerical Python library.
  • NumPy contains a multi-dimentional array and matrix data structures.
  • It can be utilised to perform a number of mathematical operations on arrays such as trigonometric, statistical and algebraic routines.
  • NumPy is an extension of Numeric and Numarray.
  • The library contains a large number of mathematical, algebraic and transformation functions .
  • It also contains random number generators.
  • NumPy is a wrapper around a library implemented in C.
  • Pandas objects heavily relies on NumPy objects. Pandas extends Numpy.

    How Do I Install Numpy?

Use pip to install NumPy package:

pip install numpy

SciPy stack also contains the NumPy packages

Photo by Chris Ried on Unsplash

Pandas and Numpy complement each other and are the two most important Python libraries.

If you want to understand how Pandas work then please have a look at

What Are The Most Important Numpy Data Types?

There are a large number of NumPy objects available:

One Dimensional Array

One of the most important objects are N-dimensional array type known as ndarray. All of the items that are stored in ndarray are required to be of same type.

An array contains a collection of objects of same type such as integers.

Think of an one dimensional array as a column or a row of a table with one or more elements:

To create an array:

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

Multi-Dimensional Array

A multidimentional array has more than one column.

Imagine an Excel Spreadsheet — it has columns and row. Each column can be considered as a dimension. This is a 2-D Array.

We can instantiate an array object:

numpy.array([,.,.,.,])
e.g.
numpy.array([1,2]) #1D
numpy.array([[1,2],[10,20]]) #2D
#For complex types
numpy.array([1,2], dtype=complex) #1D complex

If you want to create a 3-D Array:

3DArray = np.random.randint(10, size=(3, 4, 5))

There are also other types available such as:

  1. Boolean
  2. Integer (signed and unsigned)
  3. Float
  4. Complex

    Different Ways To Create An Array

There are a number of different ways to create an array. This section will provide an overview of the most common methodologies:

  1. If you want to create an array without any element:
numpy.empty(2) #this will create 1D array of 2 elements
numpy.empty(2,3) #this will create 2D array (2 rows, 3 columns each)

2. If you want to create an array with 0s:

numpy.zeros(2) #it will create an 1D array with 2 elements, both 0
#Note the parameter of the method is shape, it could be int or a tuple

3. If you want to create an array with 1s:

numpy.ones(2) # this will create 1D array with 2 elements, both 1

4. If you want to create a Numpy array from Python sequence of elements:

numpy.asarray([python sequence]) #e.g. numpy.asarray([1,2])

5. A text can be created as an array:

numpy.frombuffer('hi')
#frombuffer() takes in any object that exposes buffer interface

We can pass in dtype parameter, default is float.

6. If you want to create a range of elements:

import numpy as np
array = np.arange(3)
#array will contain 0,1,2

7. If you want to create an array with values that are evenly spaced:

numpy.arange(first, last, step, type)
#without last, step and type, the function behaves like arange()
e.g. to create 0-5, 2 apart
numpy.array(0,6,2) will return [0,2,4]

8. If you want to create an array where the values are linearly spaced between an interval then use:

numpy.linspace(first, last, number)
e.g.
numpy.linspace(0,10,5) will return [0,2.5,5,7.5,10]

9. If you want to create an array where the values are log spaced between an interval then use:

numpy.logspace(first, end, number)

Any base can be specified, Base10 is the default.

10. Random number generation

Use the random module of numpy for uniformly distributed numbers:

np.random.rand(3,2) #3 rows, 2 cols

Adding/Removing/Sorting Elements

To add elements:

np.append(a, [1,2]) #adds 1,2 at the end
#insert can also be used if we want to insert along a given index

To delete elements:

np.delete(array, 1) #1 is going to be deleted from the array

Sorting

To sort an array, call the sort(array, axis, kind, orderby) function:

np.sort(array1, axis=1, kind = 'quicksort', order ='column name')

Photo by Mikael Kristenson on Unsplash

NumPy Array Functions And Attributes

An ndarray object has a number of attributes, such as:

  1. shape: To find the dimensions (numbers of column/row) of an array:
array = np.array([[..],[..]])
array.shape

You can change the shape (resize) an array by setting the shape property:

array.shape = (1,2) #1 row, 2 columns

2. resize(x,y) can also be used to resize an array

3. If you want to find the number of dimensions of an array:

array.dim

4. If you want to find length of each element of an array:

array.itemsize

It will then return the length of an element in bytes.

5. If you want to slice a subset of an array:

array = np.arange(100)
#Get 3rd element:
array[2]
#Get items within indexes
array[3:5] #3 is start, 5 is end
#Get 3-10 element, step size 4 increments:
array[2:9:4]
#Get all elements from 2nd element onwards
array[1:]
#Can also pass in N-Dimensional Index
array[[0,1],[1,2]]

6. Conditions In Array Slicing

We can pass in boolean operators e.g.

Get all NAN elements

array[np.isnan(array)]

where() can be used to pass in boolean expressions:

np.where(array > 5) # will return all elements that meet the criteria

7. Broadcasting an array

When a mathematical operation is performed on two arrays of different sizes then the smaller array is broadcasted to the size of the larger array:

bigger_array = arange(5,3) #5 rows, 3 columns array
smaller_array = arange(5) #5 rows, 1 column array
final_array = bigger_array + smaller_array

8. Transposing Array

array.T
rollaxis, swapaxes, transpose are also available transpose functions.

9. To join arrays:

np.concatenate(a,b)
np.stack(a,b)
np.hstack(a,b)
np.vstack(a,b)

10. String Operations

A large number of string operations can be utilised e.g.

add(), upper(), lower(), replace() etc.

11. To create a deep copy of numpy array:

new_array = np.copy(array)

Mathematical Functions

Numpy offers a range of powerful Mathematical functions such as

Add, Subtract, Multiple, Divide, Power, Mod

To perform basic arithmetic functions:

np.add(array1, array2)
np.subtract(array1, array2)
np.multiply(array1, array2)
np.divide(array1, array2)
np.pow(array1, array2) 
np.pow(array1, integer)
#to get remainder
np.mod(array1, array2)
np.remainder(array1, array2)

Rounding, Ceil, Floor

To change the precision of all elements of an array:

np.around(array, 4) # 4dp
np.ceil(array) #1.8 will become 2
np.floor(array) #1.8 will become 1

Trigonometric

array = np.arange(10)
np.sin(array)
np.cos(array)
np.tan(array)
np.arcsin(array)
np.arcos(array)
np.arctan(array)

A number of complex number functions can also be applied such as getting real or imaginary parts of an array with complex numbers.

Statistical

There are also a large number of statistical functions available:

np.amin(array1, axis) #min in the axis
np.amax(array1, axis) #max in the axis
np.percentile(array1, percentile)
Additionally, following functions are available:
np.median(), np.st(), np.average(), np.mean(), np.var()

Algebra

Numpy contains a module which is known as linalg. It is rich with a number of algebraic functions:

1. dot() #dot product of two arrays
2. inner() #inner product of two arrays
3. determinant() #determinant of an array
4. solve() #solves matrix equation
5. inv() #inverse of matrix
6. matmul() #matrix product of two arrays

Summary

This article provided an overview of the core functionalities of the NumPy library. Since NumPy was incorporated with the features of Numarray in 2005, it has gained huge popularity and is considered to be one of the key Python libraries to use.

The article outlined key functions and attributes of NumPy array.

Please let me know if you have any feedback, what your favourite NumPy features are and if you like these types of articles to be blogged in the future.

Hope it helps

numpy python data-science machine-learning

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Data Science Projects | Data Science | Machine Learning | Python

Practice your skills in Data Science with Python, by learning and then trying all these hands-on, interactive projects, that I have posted for you.

Data Science Projects | Data Science | Machine Learning | Python

Practice your skills in Data Science with Python, by learning and then trying all these hands-on, interactive projects, that I have posted for you.

Data Science Projects | Data Science | Machine Learning | Python

Practice your skills in Data Science with Python, by learning and then trying all these hands-on, interactive projects, that I have posted for you.

Data Science Projects | Data Science | Machine Learning | Python

Practice your skills in Data Science with Python, by learning and then trying all these hands-on, interactive projects, that I have posted for you.

Data Science Projects | Data Science | Machine Learning | Python

Practice your skills in Data Science with Python, by learning and then trying all these hands-on, interactive projects, that I have posted for you.