NumPy – as the name suggests, it stands for Numerical Python, it’s a fundamental array processing package deal in python which presents gear for managing the n-dimensional arrays. It provides diverse functionality which includes complete mathematical functions & provides scientific operations related to linear algebra, statistics.
The users of NumPy usually encompass one who is a starting coder to skilled researchers doing cutting-edge clinical and business studies & development. The NumPy API is used drastically in Pandas, SciPy, Matplotlib, sci-kit-learn, scikit-picture, and maximum different statistics technology and Data Analysis Python packages.
The NumPy library also does include multidimensional array and matrix statistics systems. It offers a homogeneous n-dimensional array object with strategies to successfully function on it. NumPy executes huge kind of mathematical operations on arrays. It provides effective statistics systems to Python that ensure precise calculations with arrays and matrices.
Table of Content
- How to import NumPy?
- Python List Vs NumPy Array
- Why use NumPy
- Creating a NumPy Array
- Basic ndarray
- Array of zeros
- Array of ones
- The Shape and Reshaping of NumPy Array
- How do you know shape and size of an array?
- Number of dimensions, size & shape of nd-array
- Reshape an array
- Adding, removing and sorting elements
- Transpose an array
- Indexing and Slicing of NumPy Array
- Slicing 1-D NumPy arrays
- Slicing 2-D NumPy arrays
- Slicing 3-D NumPy arrays
- Stacking NumPy Array
- Using vstack
- Using hstack
- Broadcasting NumPy Array
How to Import Numpy
Now the question you must have been asking yourself – How to import NumPy?
To apply a package or library to your code, one needs to make it accessible. In order to begin the usage of NumPy and all the capabilities to be had in NumPy, first, it needs to be imported. This may be without difficulty performed with this import statement:
import numpy as np
We have something called ‘as np’ that is used so that we can just use ‘np’ instead of writing ‘numpy’ all over the code, which helps reduce the code and our program would look simpler. The core of NumPy is the ‘ndarray’, where nd means n-dimensional. This is similar to the data type in the list, but with slight differences.
Python List Vs NumPy Array
As a novice in the world of Python, you might be wondering why we’re using NumPy arrays instead of Python lists. After all, these Python lists function as an array that can hold multiple types of entries. This is an excellent question, and the answer can be found in the way Python stores objects in memory.
A Python object is essentially a pointer to a memory region that keeps all of the object’s characteristics, such as bytes and length & the value. Although this greater record is what makes Python a dynamically typed language, it additionally comes at a value that will become obvious whilst storing a massive series like in an array.
Python lists are basically an array of pointers, every pointing to a place that incorporates the records associated with the element. This provides numerous overheads in phrases of reminiscence and computation. And a maximum of these records is rendered redundant whilst all of the gadgets saved inside the listing are of the identical type!
To triumph over this problem, we use NumPy arrays that include the best homogeneous factors, i.e. factors having the identical information type. This makes it greater green at storing and manipulating the array. This distinction will become obvious whilst the array has a massive quantity of factors, say hundreds of millions. Also, with NumPy arrays, you could carry out element-smart operations, something which isn’t always feasible with the use of Python lists!
This is the purpose why NumPy arrays are desired over Python lists whilst appearing mathematical operations on a massive quantity of information.
Why use NumPy?
Python wasn’t at first designed for numerical computation. It’s inherently slower than compiled languages like C, but NumPy fills that gap. Following are few benefits of NumPy
- It provides economical dimensional array operations, each memory and computation wise
- It provides quick mathematical operations on entire array while not ought to use loop
- It conjointly provides scientific operations involving linear algebra, statistics, Fourier remodel and a lot of
- It provides tool for ability with c and c++
Creating a NumPy Array
NumPy arrays are very easy to create given the complex problems they solve. To create a very simple ndarray, use the np. array () method. All to be done is pass the values of the array as a list:
import numpy as np np.array([0,1,2,3,4]) output: array([0,1,2,3,4)]
Arrays of Zeroes
NumPy lets also create an array of all zeros by using the np. zeros() method. All that have to be done is pass the shape of the desired array:
import numpy as np np.zeros() output: array([0,0,0])
The one above is a 1-D array while the one below is a 2-D array:
import numpy as np np.zeros([3,3]) output: array([0.,0.,0.], [0.,0.,0.], [0.,0.,0.]])
Array of ones
The alike array of zeros, one can also form an array of all 1s using the np. ones() method:
import numpy as np np.ones() output: array([1,1,1])
Return evenly spaced values within a given interval. For instance :
import numpy as np np.arange(4) output: array([0,1,2,3])
Return evenly spaced numbers over a specified interval. NumPy linspace function creates sequences of evenly spaced values within a defined interval
import numpy as np np.linspace(2,3,num=5) output: array([2.,2.25,2.5,2.75,3.])
Array operation (max() , min(), sum())
By the terms max, min & sum it’s clear that it will give the respective largest array, smallest array, and sum of the array.
import numpy as np arr = np.array([1,2,3]) print("max array: " , arr.max()) print("min array: " , arr.min()) print("sum of array: " , arr.sum()) output: max array: 3 min array: 1 sum of array: 6
The Shape and Size of NumPy Array
Post done creating a ndarray, the next thing one would want to do is explore an inch more the shape, and the size of the ndarray to play around more and thus in the process learn more
np.ndim () – will display the number of axes, or dimensions, of the array.
import numpy as np arr = np.array([[1,2,3],[4,5,6]]) arr.ndim output: 2
np.size () – displays the total number of elements of the array. This is the product of the elements of the array’s shape.
import numpy as np arr = np.array([[1,2,3],[4,5,6]]) arr.size output: 6
np.shape() – displays a tuple of integers that indicate the number of elements stored along each dimension of the array. If, for example, you have a 2D array with 2 rows and 3 columns, the shape of your array is (2,3).
import numpy as np arr = np.array([[1,2,3],[4,5,6]]) arr.shape output: (2,3)
Reshape an array
Reshaping a ndarray can be done using the np. reshape () method. It changes the shape of the ndarray without changing the data within the ndarray:
While using the reshape method, the array one wants to produce needs to have the same number of elements as the original array. For instance, if you start with an array with 9 elements, you’ll need to make sure that your new array also has a total of 9 elements.
import numpy as np arr = np.array([1,2,3,4,5,6,7,8,9]) reshape_arr = a.reshape(3,3) reshape_arr output: array([1,2,3] [4,5,6] [7,8,9])
Adding, removing and sorting elements
The following are supposed to be executed to add, remove & sort any array respectively :
To append() :
One needs to add elements to the array at any time with np. append(). Make sure to specify the array and the elements you want to include. For example:
import numpy as np arr = np.array([1,2,3]) np.append(arr ,[["a,"b","c"],[7,8,9]]) output: array([1,2,3,"a","b","c",7,8,9]
To delete(): to delete a particular array you have to give the index of an array as shown below and axis
import numpy as np arr = np.array([[1,2,3],[4,5,6],[7,8,9]]) np.delete(arr,1,0) # (array ,index ,axis) output: array([[1,2,3], [7,8,9]])
To sort(): sorting the array by default is in acceding order \
import numpy as np arr = np.array([[3,2,4],[5,0,1]]) np.sort(arr) output: array([2 3 4] [0 1 5])
Transpose an array
Another interesting reshaping method of NumPy is the transpose () method. It does take the input array that’s feed-in and swaps the rows with the column values, and the column values with the values of the rows:
import numpy as np arr = np.array([[1,2,3],[4,5,6]]) np.transpose(arr) output: array([1 4] [2 5] [3 6])
Indexing and Slicing of NumPy Array
So far, we have studied how to create a NumPy array and therefore how to determine the size, shape, dimension of the same. Here, we will learn what’s the way to extract specific values from the array using indexing and slicing. For instance:
Slicing 1-D NumPy arrays
import numpy as np a = np.array([1,2,3,4,5]) a[1:5:2] output: array([2, 4])
Slicing 2-D NumPy arrays: it’s too easy only takes 2 parameters:
import numpy as np a = np.array([[1,2,3],[4,5,6],[7,8,9]]) a[:2,1:] output: array([[2, 3], [5, 6]])
Slicing 3-D NumPy arrays: we have to pass 3 parameters for slicing in 3d :
( axis , rows , columns)
import numpy as np a = np.array([ [[10,11,12],[13,14,15],[16,17,18]], [[20,21,22],[23,24,25],[26,27,28]], [[29,30,31],[32,33,34],[35,36,37]]]) a[0: ,1:3,:] output: array([[[13, 14, 15], [16, 17, 18]], [[23, 24, 25], [26, 27, 28]], [[32, 33, 34], [35, 36, 37]]])
Stacking NumPy array
To stack two existing arrays, both vertically and horizontally we can use: –
- vstack() : stacking two or more array vertically
- hstack() : stacking two or more array horizontally
For vstack(), Let’s say:
arr_1 = np.array([[1,2],[3,4]]) arr_2 = np.array([[5,6],[7,8]]) np.vstack((arr_1,arr_2)) output: array([[1, 2], [3, 4], [5, 6], [7, 8]])
For hstack(), Let’s say:
import numpy as np arr_1 = np.array([[1,2],[3,4]]) arr_2 = np.array([[5,6],[7,8]]) np.hstack((arr_1,arr_2)) output: array([[1, 2, 5, 6], [3, 4, 7, 8]])
Broadcasting NumPy Array
Broadcasting describes how NumPy treats arrays with distinctive shapes all through mathematics operations. Subject to positive constraints, the smaller array is “broadcast” throughout the bigger array so that they’ve like minded shapes. Broadcasting offers a way of vectorizing array operations in order that looping takes place in C in place of Python. It does this without making pointless copies of facts and commonly results in green set of rules implementations.
import numpy as np arr = np.array([1,2,3,4]) arr*3 output: array([ 3, 6, 9, 12])
I hope you are clear with numpy concept from basic to advance if any doubts regarding numpy just comment out we will reply and make your doubts clear as soon as possible in next blog we will focus on Pandas Data Science library.