Why Should We Use NumPy?Understanding NumPy Features Before Re-Inventing The WheelFarhad MalikBlockedUnblockFollowFollowingMar 31NumPy 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, please read:Everything About Python — Beginner To AdvanceEverything You Need To Know In One Articlemedium.
comPlease read FinTechExplained disclaimer.
It’s best to understand what Numpy offers than to re-invent the wheelWhat 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.
NumPy extends Pandas.
How Do I Install Numpy?Use pip to install NumPy package:pip install numpySciPy stack also contains the NumPy packagesPhoto by Dlanor S on UnsplashPandas 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 thisDid You Know Pandas Can Do So Much?Don’t Code Python Without Exploring Pandas Firstmedium.
comWhat Are The Most Important Numpy Data Types?There are a large number of NumPy objects available:One Dimensional ArrayOne 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 ArrayA 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]) #1Dnumpy.
array([[1,2],[10,20]]) #2D#For complex typesnumpy.
array([1,2], dtype=complex) #1D complexIf 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:BooleanInteger (signed and unsigned)FloatComplexDifferent Ways To Create An ArrayThere are a number of different ways to create an array.
This section will provide an overview of the most common methodologies:If you want to create an array without any element:numpy.
empty(2) #this will create 1D array of 2 elementsnumpy.
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 tuple3.
If you want to create an array with 1s:numpy.
ones(2) # this will create 1D array with 2 elements, both 14.
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 interfaceWe can pass in dtype parameter, default is float.
6.
If you want to create a range of elements:import numpy as nparray = range(3)#array will contain 0,1,27.
If you want to create an array with values that are evenly spaced:numpy.
arrange(first, last, step, type)#without last, step and type, the function behaves like arrange()e.
g.
to create 0-5, 2 apartnumpy.
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 generationUse the random module of numpy for uniformly distributed numbers:np.
random.
rand(3,2) #3 rows, 2 colsAdding/Removing/Sorting ElementsTo 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 indexTo delete elements:np.
delete(array, 1) #1 is going to be deleted from the arraySortingTo 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 UnsplashNumPy Array Functions And AttributesAn ndarray object has a number of attributes, such as:shape: To find the dimensions (numbers of column/row) of an array:array = np.
array([[.
],[.
]])array.
shapeYou can change the shape (resize) an array by setting the shape property:array.
shape = (1,2) #1 row, 2 columns2.
resize(x,y) can also be used to resize an array3.
If you want to find the number of dimensions of an array:array.
dim4.
If you want to find length of each element of an array:array.
itemsizeIt will then return the length of an element in bytes.
5.
If you want to slice a subset of an array:array = np.
arrange(100)#Get 3rd element:array[2]#Get items within indexesarray[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 onwardsarray[1:]#Can also pass in N-Dimensional Indexarray[[0,1],[1,2]]6.
Conditions In Array SlicingWe can pass in boolean operators e.
g.
Get all NAN elementsarray[np.
isnan(array)]where() can be used to pass in boolean expressions:np.
where(array > 5) # will return all elements that meet the criteria7.
Broadcasting an arrayWhen 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 = arrange(5,3) #5 rows, 3 columns arraysmaller_array = arrange(5) #5 rows, 1 column arrayfinal_array = bigger_array + smaller_array8.
Transposing Arrayarray.
Trollaxis, 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 OperationsA 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 FunctionsNumpy offers a range of powerful Mathematical functions such asAdd, Subtract, Multiple, Divide, Power, ModTo 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 remaindernp.
mod(array1, array2)np.
remainder(array1, array2)Rounding, Ceil, FloorTo change the precision of all elements of an array:np.
around(array, 4) # 4dpnp.
ceil(array) #1.
8 will become 1np.
floor(array) #1.
8 will become 2Trigonometricarray = np.
arrange(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.
StatisticalThere are also a large number of statistical functions available:np.
amin(array1, axis) #min in the axisnp.
amax(array1, axis) #max in the axisnp.
percentile(array1, percentile)Additionally, following functions are available:np.
median(), np.
st(), np.
average(), np.
mean(), np.
var()AlgebraNumpy contains a module which is known as linalg.
It is rich with a number of algebraic functions:1.
dot() #dot product of two arrays2.
inner() #inner product of two arrays3.
determinant() #determinant of an array4.
solve() #solves matrix equation5.
inv() #inverse of matrix6.
matmul() #matrix product of two arraysSummaryThis 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.. More details