NumPy class 11th
NumPy class 11th
What is NumPy?
NumPy stands for Numerical Python, is an open-source Python library that provides support for large, multi-
dimensional arrays and matrices.It 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.
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.
Import NumPy
Once NumPy is installed, import it in your applications by adding the import keyword:
import numpy
or
import numpy as np
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
print(arr)
print(type(arr))
output:
[1 2 3 4 5]
<class 'numpy.ndarray'>
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
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 = np.array(42)
print(arr)
1-D Arrays
import numpy as np
print(arr)
2-D Arrays
import numpy as np
print(arr)
3-D arrays
import numpy as np
print(arr)
Array indexing is the same as accessing an array element.You can access an array element by referring to its
index number.The 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
print(arr[0])
or
import numpy as np
print(arr[-4])
The NumPy array object has a property called dtype that returns the data type of the array:
Example:
import numpy as np
print(arr.dtype)
output: int64
Example:
x = arr.copy()
arr[0] = 42
print(arr)
print(x)
output:
[42 2 3 4 5]
[1 2 3 4 5]
import numpy as np
print(arr.shape)
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 array.The shape of an array is the number of elements in each
dimension.By reshaping we can add or remove dimensions or change number of elements in each dimension.
Example:
import numpy as np
newarr = arr.reshape(4, 3)
print(newarr)
output:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
Iterating means going through elements one by one.As we deal with multi-dimensional arrays in numpy, we can
do this using basic for loop of python.If 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
for x in arr:
print(x)
Example:
import numpy as np
for x in arr:
print(x)
Example:
import numpy as np
for x in arr:
for y in x:
print(y)
Example:
import numpy as np
print(arr)
output: [1 2 3 4 5 6]
Example:
import numpy as np
print(arr)
output:
[[1 2 5 6]
[3 4 7 8]]
Splitting is reverse operation of Joining.Joining 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
newarr = np.array_split(arr, 3)
print(newarr)
output:
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
x = np.where(arr == 4)
print(x)
output:
(array([3, 5, 6]),)
Sorting Arrays
Sorting means putting elements in an ordered sequence.Ordered sequence is any sequence that has an order
corresponding to elements, like numeric or alphabetical, ascending or descending.The NumPy ndarray object has
a function called sort(), that will sort a specified array.
Example:
import numpy as np
print(np.sort(arr))
Array Slicing is the process of extracting a portion of an array.With slicing, we can easily access elements in the
array. It can be done on one or more dimensions of a NumPy array.
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.
In NumPy, it's possible to access the portion of an array using the slicing operator
import numpy as np
# create a 1D array
print(array1[0:8:2]) # [1 5 8 2]
print(array1[3:]) # [7 8 9 2 4 6]
print(array1[:]) # [1 3 5 7 8 9 2 4 6]
import numpy as np
numbers[1:5:2] = 16
print(numbers)
# Output: [ 2 16 6 16 10 12]
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
print(numbers[-3:]) # [8 10 12]
print(numbers[-5:-2]) # [4 6 8]
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.
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
print(array1[:2, :2])
# Output
[[ 1 3]
[ 9 11]]
Example:
import numpy as np
# create a 2D array
[2, 4, 6, 8]])
# slice the array to get the first two rows and columns
# slice the array to get the last two rows and columns
[[ 1 3]
[ 9 11]]
[[13 15]
[ 6 8]]
Some time you need to create empty array or an uninitialized array of specified shape and dtype
numpy.empty(shape,dtype,order=’C’ or ‘F’)
import numpy as np
arr1=np.empty([3,2])
arr2=np.empty([3,2],dtype=np.int32)
To create an array with specifies size and type but filled with zero we can use zeros().
numpy.zeros(shape,dtype,order=’C’ or ‘F’)
import numpy as np
arr1=np.zeros([3,2])
arr2=np.zeros([3,2],dtype=np.int32)
To create an array with specifies size and type but filled with ones we can use ones().
numpy.ones(shape,dtype,order=’C’ or ‘F’)
import numpy as np
arr1=np.ones([3,2])
arr2=np.ones([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.
numpy.arrange(start,stop,step,dtype)
import numpy as np
arr1=np.arange(7)
arr2=np.arange(1,7)
arr3=np.arange(1,7,2)
arr4=np.arange(7,dtype=int32)
Some time , you need evenly spaced elements between two given limits. For this purpose, NumPy provides
linspace().
import numpy as np
arr1=np.linspace(2,3,6)