NumPy
What is NumPy?
NumPy stands for Numerical Python, is an open-source Python library that provides support for large, multi-
dimensional arrays and [Link] also have a collection of high-level mathematical functions to operate on
arrays. It also has functions for working in domain of linear algebra and matrices.
Why Use NumPy?
NumPy arrays are stored at one continuous place in memory unlike lists, so processes can access and
manipulate them very efficiently.
In Python we have lists that serve the purpose of arrays, but they are slow to process.
NumPy aims to provide an array object that is up to 50x faster than traditional Python lists.
The array object in NumPy is called ndarray, it provides a lot of supporting functions that make working
with ndarray very easy.
Arrays are very frequently used in data science, where speed and resources are very important.
Installation of NumPy
If you have Python and PIP already installed on a system, then installation of NumPy is very easy.
Install it using this command: C:\Users\Your Name>pip install numpy
Import NumPy
Once NumPy is installed, import it in your applications by adding the import keyword:
import numpy
or
import numpy as np
Now NumPy is imported and ready to use.
Create a NumPy ndarray Object
NumPy is used to work with arrays. The array object in NumPy is called ndarray. We can create a NumPy
ndarray object by using the array() function.
Example:
import numpy as np
arr = [Link]([1, 2, 3, 4, 5])
print(arr)
print(type(arr))
output:
[1 2 3 4 5]
<class '[Link]'>
To create an ndarray, we can pass a list, tuple or any array-like object into the array() method, and it will be
converted into an ndarray:
import numpy as np
arr = [Link]((1, 2, 3, 4, 5))
print(arr)
Dimensions in Arrays
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.
Example:
import numpy as np
arr = [Link](42)
print(arr)
1-D Arrays
These are the most common and basic arrays.
import numpy as np
arr = [Link]([1, 2, 3, 4, 5])
print(arr)
2-D Arrays
These are often used to represent matrix or 2nd order tensors.
import numpy as np
arr = [Link]([[1, 2, 3], [4, 5, 6]])
print(arr)
3-D arrays
import numpy as np
arr = [Link]([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arr)
NumPy Array Indexing
Array indexing is the same as accessing an array [Link] can access an array element by referring to its
index [Link] indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the
second has index 1 etc.
Example:
import numpy as np
arr = [Link]([1, 2, 3, 4])
print(arr[0])
or
import numpy as np
arr = [Link]([1, 2, 3, 4])
print(arr[-4])
Checking the Data Type of an Array
The NumPy array object has a property called dtype that returns the data type of the array:
Example:
import numpy as np
arr = [Link]([1, 2, 3, 4])
print([Link])
output: int64
NumPy Array Copy
Example:
arr = [Link]([1, 2, 3, 4, 5])
x = [Link]()
arr[0] = 42
print(arr)
print(x)
output:
[42 2 3 4 5]
[1 2 3 4 5]
Get the Shape of an Array
import numpy as np
arr = [Link]([[1, 2, 3, 4], [5, 6, 7, 8]])
print([Link])
The example above returns (2, 4), which means that the array has 2 dimensions, where the first dimension has 2
elements and the second has 4.
Reshaping arrays
Reshaping means changing the shape of an [Link] shape of an array is the number of elements in each
[Link] reshaping we can add or remove dimensions or change number of elements in each dimension.
Example:
import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = [Link](4, 3)
print(newarr)
output:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
NumPy Array Iterating
Iterating means going through elements one by [Link] we deal with multi-dimensional arrays in numpy, we can
do this using basic for loop of [Link] we iterate on a 1-D array and 2-D array it will go through each element
one by one.
Example:
import numpy as np
arr = [Link]([1, 2, 3])
for x in arr:
print(x)
Example:
import numpy as np
arr = [Link]([[1, 2, 3], [4, 5, 6]])
for x in arr:
print(x)
Example:
import numpy as np
arr = [Link]([[1, 2, 3], [4, 5, 6]])
for x in arr:
for y in x:
print(y)
Joining NumPy Arrays
Joining means putting contents of two or more arrays in a single [Link] SQL we join tables based on a key,
whereas in NumPy we join arrays by [Link] pass a sequence of arrays that we want to join to the
concatenate() function, along with the axis. If axis is not explicitly passed, it is taken as 0.
Example:
import numpy as np
arr1 = [Link]([1, 2, 3])
arr2 = [Link]([4, 5, 6])
arr = [Link]((arr1, arr2))
print(arr)
output: [1 2 3 4 5 6]
Example:
import numpy as np
arr1 = [Link]([[1, 2], [3, 4]])
arr2 = [Link]([[5, 6], [7, 8]])
arr = [Link]((arr1, arr2), axis=1)
print(arr)
output:
[[1 2 5 6]
[3 4 7 8]]
Splitting NumPy Arrays
Splitting is reverse operation of [Link] merges multiple arrays into one and Splitting breaks one array into
multiple. We use array_split() for splitting arrays, we pass it the array we want to split and the number of splits.
Example:
import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6])
newarr = np.array_split(arr, 3)
print(newarr)
output:
[array([1, 2]), array([3, 4]), array([5, 6])]
Searching Arrays
You can search an array for a certain value, and return the indexes that get a match. To search an array, use the
where() method.
Example:
import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 4, 4])
x = [Link](arr == 4)
print(x)
output:
(array([3, 5, 6]),)
Sorting Arrays
Sorting means putting elements in an ordered [Link] sequence is any sequence that has an order
corresponding to elements, like numeric or alphabetical, ascending or [Link] NumPy ndarray object has
a function called sort(), that will sort a specified array.
Example:
import numpy as np
arr = [Link]([3, 2, 0, 1])
print([Link](arr))
NumPy Array Slicing
Array Slicing is the process of extracting a portion of an [Link] slicing, we can easily access elements in the
array. It can be done on one or more dimensions of a NumPy array.
Syntax of NumPy Array Slicing
array[start:stop:step]
start - index of the first element to be included in the slice
stop - index of the last element (exclusive)
step - step size between each element in the slice
Note: When we slice arrays, the start index is inclusive but the stop index is exclusive.
If we omit start, slicing starts from the first element
If we omit stop, slicing continues up to the last element
If we omit step, default step size is 1
1D NumPy Array Slicing
In NumPy, it's possible to access the portion of an array using the slicing operator
import numpy as np
# create a 1D array
array1 = [Link]([1, 3, 5, 7, 8, 9, 2, 4, 6])
# slice array1 from index 2 to index 6 (exclusive)
print(array1[2:6]) # [5 7 8 9]
# slice array1 from index 0 to index 8 (exclusive) with a step size of 2
print(array1[Link]) # [1 5 8 2]
# slice array1 from index 3 up to the last element
print(array1[3:]) # [7 8 9 2 4 6]
# items from start to end
print(array1[:]) # [1 3 5 7 8 9 2 4 6]
Modify Array Elements Using Slicing
import numpy as np
# create a numpy array
numbers = [Link]([2, 4, 6, 8, 10, 12])
# modify every second element from indices 1 to 5
numbers[Link] = 16
print(numbers)
# Output: [ 2 16 6 16 10 12]
NumPy Array Negative Slicing
We can also use negative indices to perform negative slicing in NumPy arrays. During negative slicing, elements
are accessed from the end of the array.
Example.
import numpy as np
# create a numpy array
numbers = [Link]([2, 4, 6, 8, 10, 12])
# slice the last 3 elements of the array
# using the start parameter
print(numbers[-3:]) # [8 10 12]
# slice elements from 2nd-to-last to 4th-to-last element
# using the start and stop parameters
print(numbers[-5:-2]) # [4 6 8]
# slice every other element of the array from the end
# using the start, stop, and step parameters
print(numbers[-1::-2]) # [12 8 4]
2D NumPy Array Slicing
A 2D NumPy array can be thought of as a matrix, where each element has two indices, row index and column
index.
To slice a 2D NumPy array, we can use the same syntax as for slicing a 1D NumPy array. The only difference is
that we need to specify a slice for each dimension of the array.
Syntax of 2D NumPy Array Slicing
array[row_start:row_stop:row_step, col_start:col_stop:col_step]
row_start,row_stop,row_step - specifies starting index, stopping index, and step size for the rows
respectively
col_start,col_stop,col_step - specifies starting index, stopping index, and step size for the columns
respectively
# create a 2D array
array1 = [Link]([[1, 3, 5, 7],
[9, 11, 13, 15]])
print(array1[:2, :2])
# Output
[[ 1 3]
[ 9 11]]
Example:
import numpy as np
# create a 2D array
array1 = [Link]([[1, 3, 5, 7],
[9, 11, 13, 15],
[2, 4, 6, 8]])
# slice the array to get the first two rows and columns
subarray1 = array1[:2, :2]
# slice the array to get the last two rows and columns
subarray2 = array1[1:3, 2:4]
# print the subarrays
print("First Two Rows and Columns: \n",subarray1)
print("Last two Rows and Columns: \n",subarray2)
First Two Rows and Columns:
[[ 1 3]
[ 9 11]]
Last two Rows and Columns:
[[13 15]
[ 6 8]]
Ways to Cerate NumPy Arrays
(i) Creating empty arrays using empty()
Some time you need to create empty array or an uninitialized array of specified shape and dtype
[Link](shape,dtype,order=’C’ or ‘F’)
import numpy as np
arr1=[Link]([3,2])
arr2=[Link]([3,2],dtype=np.int32)
empty() create array with any random generated values
(ii) Creating array filled zeros() .
To create an array with specifies size and type but filled with zero we can use zeros().
[Link](shape,dtype,order=’C’ or ‘F’)
import numpy as np
arr1=[Link]([3,2])
arr2=[Link]([3,2],dtype=np.int32)
(iii) Creating array filled ones() .
To create an array with specifies size and type but filled with ones we can use ones().
[Link](shape,dtype,order=’C’ or ‘F’)
import numpy as np
arr1=[Link]([3,2])
arr2=[Link]([3,2],dtype=np.int32)
(iv) Creating arrays with a numerical range using arrange()
arrang() creates a NumPy array with evenly spaced values within specified numerical range.
[Link](start,stop,step,dtype)
import numpy as np
arr1=[Link](7)
arr2=[Link](1,7)
arr3=[Link](1,7,2)
arr4=[Link](7,dtype=int32)
(v) Creating arrays with a numerical range using linspace()
Some time , you need evenly spaced elements between two given limits. For this purpose, NumPy provides
linspace().
numpy. linespace(start,stop,number of values to be generated)
import numpy as np
arr1=[Link](2,3,6)