0% found this document useful (0 votes)
2 views51 pages

Numpy Matplotlib Panda STD

NumPy is a powerful Python library for efficient mathematical and numerical operations, particularly with large multi-dimensional arrays. It provides various functions for creating arrays, performing arithmetic operations, and statistical analysis, as well as capabilities for reshaping and iterating through arrays. The library significantly enhances computational speed compared to traditional Python lists, making it essential for data science applications.

Uploaded by

Aritra Das
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views51 pages

Numpy Matplotlib Panda STD

NumPy is a powerful Python library for efficient mathematical and numerical operations, particularly with large multi-dimensional arrays. It provides various functions for creating arrays, performing arithmetic operations, and statistical analysis, as well as capabilities for reshaping and iterating through arrays. The library significantly enhances computational speed compared to traditional Python lists, making it essential for data science applications.

Uploaded by

Aritra Das
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to NumPy

• NumPy (Numerical Python) is a powerful Python library that handles mathematical


and numerical operations efficiently.
• The main function of NumPy is to work with large, multi-dimensional arrays and to
perform complex mathematical operations between them.
• Before NumPy, numerical operations in Python relied on lists. The introduction of
NumPy arrays enhanced computational speed and efficiency considerably. The
transition from Python lists to NumPy arrays alone can boost performance by up to
100 times.
• Therefore, NumPy is a valuable asset in data science.
import numpy as np
arr = [Link]([1, 3, 5, 9])
print(arr)

Create an Array With [Link]()


The [Link]() function returns an array with values within a specified interval.

arr1 = [Link](7)
print("Using [Link](7):", arr1)
arr2 = [Link](1, 8, 2)
print("Using [Link](1, 8, 2):",arr2)
Create an Array With [Link]()
The [Link]() function is used to create an array of random numbers.

import numpy as np
arr = [Link](4)
print(arr)
N-D Array Creation From List of Lists

• To create an N-dimensional NumPy array from a Python List, we can use the

[Link]() function and pass the list as an argument.

• Create a 2-D NumPy Array

import numpy as np

arr = [Link]([[2, 5, 7, 3],

[6, 5, 2, 7]])

print(arr)
• Create a 3-D NumPy Array
• Create a 3-D NumPy array consisting of two "slices" where each slice has 3 rows and 4 columns.
import numpy as np
arr = [Link]([[[2, 4, 9, 4],
[8, 6, 7, 8],
[10, 11, 19, 12]],

[[15, 14, 18, 16],


[11, 18, 19, 20],
[11, 22, 23, 24]]])
print(arr)
Here, we created a 3D list [list of lists of lists] and passed it to the [Link]() function. This
creates the 3-D array named arr.
In the 3D list,
• The outermost list contains two elements, which are lists representing the two "slices" of the
array. Each slice is a 2-D array with 3 rows and 4 columns.
• The innermost lists represent the individual rows of the 2-D arrays.
Creating Arrays With [Link]()
The [Link]() function is used to create an array of random numbers.
import numpy as np
arr1 = [Link](3,3)
print("2-D Array: ")
print(arr1)

arr2 = [Link](3, 3, 2)
print("\n3-D Array: ")
print(arr2)
Check Number of Dimensions?
import numpy as np

a = [Link](42)
b = [Link]([1, 2, 3, 4, 5])
c = [Link]([[1, 2, 3], [4, 5, 6]])
d = [Link]([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])

print([Link])
print([Link])
print([Link])
print([Link])
Higher Dimensional Arrays
• An array can have any number of dimensions.
• When the array is created, you can define the number of dimensions by using
the ndmin argument.

import numpy as np
arr = [Link]([2, 4, 5, 9], ndmin=5)
print(arr)
print('number of dimensions :', [Link])
• Access 3-D Arrays
• To access elements from 3-D arrays we can use comma separated integers
representing the dimensions and the index of the element.
import numpy as np
arr = [Link]([[[1, 2, 3],
[4, 5, 6]],

[[7, 8, 9],
[10, 11, 12]]])
print(arr[0, 1, 2])
Shape of an Array
• The shape of an array is the number of elements in each dimension.
• NumPy arrays have an attribute called shape that returns a tuple with each index
having the number of corresponding elements

import numpy as np
arr = [Link]([[1, 2, 3, 4], [5, 6, 7, 8]])
print([Link])
• Create an array with 5 dimensions using ndmin using a vector with values 1,2,3,4
and verify that last dimension has value 4:

import numpy as np
arr = [Link]([1, 2, 3, 4], ndmin=5)
print(arr)
print('shape of array :', [Link])
Iterating Arrays
• Iterating means going through elements one by one.
• Iterate on the elements of the following 1-D array:

• import numpy as np
arr = [Link]([1, 2, 3])

for x in arr:
print(x)
Iterating 2-D Arrays
• In a 2-D array it will go through all the rows.
import numpy as np
arr = [Link]([[1, 2, 3], [4, 5, 6]])
for x in arr:
print(x)

• Iterate on each scalar element of the 2-D array:


• import numpy as np
arr = [Link]([[1, 2, 3], [4, 5, 6]])
for x in arr:
for y in x:
print(y)
Iterating 3-D Arrays
• In a 3-D array it will go through all the 2-D arrays.
• import numpy as np
arr = [Link]([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
for x in arr:
print(x)

Iterate down to the scalars:


import numpy as np
arr = [Link]([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
for x in arr:
for y in x:
for z in y:
print(z)
• Iterate through the following 3-D array:
• import numpy as np

arr = [Link]([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

for x in [Link](arr):
print(x)
Iterating With Different Step Size
• We can use filtering and followed by iteration.

• import numpy as np

arr = [Link]([[1, 2, 3, 4], [5, 6, 7, 8]])

for x in [Link](arr[:, ::2]):


print(x)
Common NumPy Attributes
Here are some of the commonly used NumPy attributes:

Attributes Description
ndim returns number of dimension of the array
size returns number of elements in the array
dtype returns data type of elements in the array
shape returns the size of the array in each dimension.
itemsize returns the size (in bytes) of each elements in the array

data returns the buffer containing actual elements of the array in memory
Most Commonly Used I/O Functions
Here are some of the commonly used NumPy Input/Output functions:

Function Description

save() saves an array to a binary file in the [Link] format.

load() loads data from a binary file in the [Link] format

savetxt() saves an array to a text file in a specific format

loadtxt() loads data from a text file.


import numpy as np
# create a NumPy array
array1 = [Link]([[1, 3, 5], [7, 9, 11]])
# save the array to a file
[Link]('[Link]', array1)

import numpy as np
# load the saved NumPy array
loaded_array = [Link]('[Link]')
# display the loaded array
print(loaded_array)
import numpy as np
# create a NumPy array
arr2 = [Link]([[1, 3, 5], [7, 9, 11]])
# save the array to a text file
[Link]('[Link]', arr2)

import numpy as np
# load the saved NumPy array
loaded_array = [Link]('[Link]')
# display the loaded array
print(loaded_array)
2-D NumPy Array Indexing

import numpy as np
# create a 2D array
arr = [Link]([[12, 11, 15, 13],
[9, 11, 7, 15],
[2, 4, 6, 8]])
# access the element at the second row and fourth column
element1 = arr[1, 3]
print("4th Element at 2nd Row:",element1)
# access the element at the first row and second column
element2 = array1[0, 1]
print("2nd Element at First Row:",element2)
Access Row or Column of 2D Array Using Indexing
import numpy as np
array1 = [Link]([[1, 3, 5],
[7, 9, 2],
[4, 6, 8]])
# access the second row of the array
second_row = array1[1, :]
print("Second Row:", second_row)
# access the third column of the array
third_col = array1[:, 2]
print("Third Column:", third_col)
3-D NumPy Array Indexing
To access an element of a 3D array, we use three indices separated by commas.
• The first index refers to the slice
• The second index refers to the row
• The third index refers to the column.

import numpy as np
array1 = [Link]([[[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]],

[[13, 14, 15, 16],


[17, 18, 19, 20],
[21, 22, 23, 24]]])

element = array1[1, 2, 1]
print(element)
1D NumPy Array Slicing

import numpy as np
array1 = [Link]([1, 3, 5, 7, 8, 9, 2, 4, 6])
print(array1[2:6])
print(array1[0:8:2])
print(array1[3:])
print(array1[:])
NumPy Array Negative Slicing
import numpy as np
numbers = [Link]([2, 4, 6, 8, 10, 12])

print(numbers[-3:])
print(numbers[-5:-2])
# slice every other element of the array from the end using the start, stop, and #step
parameters
print(numbers[-1::-2])
Reverse NumPy Array Using Negative Slicing

import numpy as np

numbers = [Link]([12, 3, 4, 6, 10, 12])


reversed_numbers = numbers[::-1]
print(reversed_numbers)
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.
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("First Two Rows and Columns: \n",subarray1)


print("Last two Rows and Columns: \n",subarray2)
NumPy Array Reshaping
NumPy array reshaping simply means changing the shape of an array without
changing its data.

import numpy as np
arr = [Link]([1, 3, 5, 7, 2, 4, 6, 8])
result = [Link](arr, (2, 4))
print(result)
Reshape 1D Array to 3D Array in NumPy

import numpy as np
array1 = [Link]([11, 12, 8, 7, 13, 14, 6, 8])
result = [Link](array1, (2, 2, 2))

print("1D to 3D Array: \n",result)


Flatten N-d Array to 1-D Array Using reshape()
• Flattening an array simply means converting a multidimensional array into a 1D array.
• To flatten an N-d array to a 1-D array we can use reshape() and pass "-1" as an argument.

import numpy as np
# flatten 2D array to 1D

arr = [Link]([[1, 3], [5, 7], [9, 11]])


result1 = [Link](arr, -1)
print("Flattened 2D array:", result1)

# flatten 3D array to 1D
arr2 = [Link]([[[1, 3], [5, 7]],
[[2, 4], [6, 8]]])
result2 = [Link](arr2, -1)
print("Flattened 3D array:", result2)
List of Arithmetic Operations
• Here's a list of various arithmetic operations along with their associated operators and
built-in functions:

Element-wise
Operator Function
Operation

Addition + add()

Subtraction - subtract()

Multiplication * multiply()

Division / divide()

Exponentiation ** power()

Modulus % mod()
import numpy as np
first_array = [Link]([1, 3, 5, 7])
second_array = [Link]([2, 4, 6, 8])

result1 = first_array + second_array


print("Using the + operator:",result1)

result2 = [Link](first_array, second_array)


print("Using the add() function:",result2)
NumPy Array Element-Wise Exponentiation

import numpy as np

arr = [Link]([1, 2, 3])

result1 = arr ** 2

print("Using the ** operator:",result1)

result2 = [Link](arr, 2)

print("Using the power() function:",result2)


NumPy Array Statistical Functions
• NumPy provides us with various statistical functions to perform statistical data analysis.

• These statistical functions are useful to find basic statistical concepts like mean, median, variance, etc.

import numpy as np

marks = [Link]([76, 78, 81, 66, 85])

mean_marks = [Link](marks)

print("Mean:",mean_marks)

median_marks = [Link](marks)

print("Median:",median_marks)

min_marks = [Link](marks)

print("Minimum marks:", min_marks)

max_marks = [Link](marks) print("Maximum marks:", max_marks)


Rounding Functions
• We use rounding functions to round the values in an array to a specified number of decimal
places.

Rounding Functions Functions

round() returns the value rounded to the desired precision

floor() returns the values of array down to the nearest integer that is less than each element

ceil() returns the values of array up to the nearest integer that is greater than each element.
import numpy as np
numbers = [Link]([1.23456, 2.34567, 3.45678, 4.56789])
# round the array to two decimal places
rounded_array = [Link](numbers, 2)
print(rounded_array)

import numpy as np
array1 = [Link]([1.23456, 2.34567, 3.45678, 4.56789])
print("Array after floor():", [Link](array1))
print("Array after ceil():", [Link](array1))
Numpy Broadcasting
• In NumPy, we can perform mathematical operations on arrays of different shapes. An
array with a smaller shape is expanded to match the shape of a larger one. This is called
broadcasting.
import numpy as np
array1 = [Link]([1, 2, 3])
array2 = [Link]([[1], [2], [3]])

# size of array1 expands to match with array2


sum = array1 + array2
print(sum)
NumPy Matrix Operations

Here are some of the basic matrix operations provided by NumPy.

Functions Descriptions

array() creates a matrix

dot() performs matrix multiplication

transpose() transposes a matrix

[Link]() calculates the inverse of a matrix

calculates the determinant of a


[Link]()
matrix

flatten() transforms a matrix into 1D array


Perform Matrix Multiplication in NumPy
We use the [Link]() function to perform multiplication between two matrices
import numpy as np
.

matrix1 = [Link]([[1, 3], [5, 7]])


matrix2 = [Link]([[2, 6], [4, 8]])

result = [Link](matrix1, matrix2)


print("matrix1 x matrix2: \n",result)
import numpy as np

# create a matrix
matrix1 = [Link]([[1, 3],
[5, 7]])

# get transpose of matrix1


result = [Link](matrix1)

print(result)
Calculate Inverse of a Matrix in NumPy
Not all matrices have an inverse. Only square matrices that have a non-zero
determinant have an inverse.

import numpy as np

matrix1 = [Link]([[1, 3, 5],


[7, 9, 2],
[4, 6, 8]])

result = [Link](matrix1)

print(result)
Find Determinant of a Matrix in NumPy

import numpy as np

# create a matrix
matrix1 = [Link]([[1, 2, 3],
[4, 5, 1],
[2, 3, 4]])

# find determinant of matrix1


result = [Link](matrix1)

print(result)
Flatten Matrix in NumPy

import numpy as np

matrix1 = [Link]([[1, 2, 3],


[4, 5, 7]])

result = [Link]()
print("Flattened 2x3 matrix:", result)
NumPy Set Operations
• A set is a collection of unique data. That is, elements of a set cannot be repeated.
• NumPy set operations perform mathematical set operations on arrays like union,
intersection, difference, symmetric difference, etc.
import numpy as np
A = [Link]([1, 3, 5])
B = [Link]([0, 2, 3])
result1 = np.union1d(A, B)
print(result1)
result2 = np.intersect1d(A, B)
print(result2)
result3 = np.setdiff1d(A, B)
print(result3)

# symmetric difference of two arrays


result4 = np.setxor1d(A, B)

print(result4)
Unique Values From a NumPy Array
• To select the unique elements from a NumPy array, we use the [Link]()
function. It returns the sorted unique elements of an array. It can also be used to
create a set out of an array.

import numpy as np
array1 = [Link]([1,1, 2, 2, 4, 7, 7, 3, 5, 2, 5])
result = [Link](array1)
print(result)
• NumPy Vectorization
• We've used the concept of vectorization many times in NumPy. It refers to
performing element-wise operations on arrays.

import numpy as np

array1 = [Link]([1, 2, 3, 4, 5 ])
number = 20

result = array1 + number

print(result)
Numpy Vectorization to Add Two Arrays Together

import numpy as np

array1 = [Link]([[1, 2, 3], [4, 5, 6]])


array2 = [Link]([[0, 1, 2], [0, 1, 2]])

array_sum = array1 + array2

print("Sum between two arrays:\n", array_sum)


NumPy Vectorization vs Python for Loop
Even though NumPy is a Python library, it inherited vectorization from C programming. As C
is efficient in terms of speed and memory, NumPy vectorization is also much faster than
Python.

import time
start = [Link]()
array1 = [1, 2, 3, 4, 5]
for i in range(len(array1)):
array1[i] += 10
end = [Link]()
print("For loop time:", end - start)
NumPy Vectorization
import numpy as np
import time
start = [Link]()
array1 = [Link]([1, 2, 3, 4, 5 ])
result = array1 + 10
end = [Link]()
print("Vectorization time:", end - start)

You might also like