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
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
There are a large number of NumPy objects available:
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])
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:
There are a number of different ways to create an array. This section will provide an overview of the most common methodologies:
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
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
An ndarray object has a number of attributes, such as:
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)
Numpy offers a range of powerful Mathematical functions such as
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)
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
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.
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()
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
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