0% found this document useful (0 votes)
3 views54 pages

Chapter 14 Python Library (Draft Note)

Chapter 14 discusses the use of libraries in Python for experimental and data analysis, explaining that libraries are collections of pre-written code that simplify common tasks. It differentiates between built-in libraries and external libraries, provides examples of both, and details how to import and use them. The chapter also covers NumPy for numerical computing, including array creation, reshaping, and basic statistical operations.

Uploaded by

siddhantgiri02
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)
3 views54 pages

Chapter 14 Python Library (Draft Note)

Chapter 14 discusses the use of libraries in Python for experimental and data analysis, explaining that libraries are collections of pre-written code that simplify common tasks. It differentiates between built-in libraries and external libraries, provides examples of both, and details how to import and use them. The chapter also covers NumPy for numerical computing, including array creation, reshaping, and basic statistical operations.

Uploaded by

siddhantgiri02
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

Chapter 14

Using Python in Experimental and Data Analysis


Problems
(Libraries in Python)

1. What is a Library in Python?

A Python library is a collection of pre-written code (functions, classes,


modules) that helps us perform common tasks without writing everything from
scratch.

2. Why Do We Need Libraries?

Suppose you want to:

• Calculate square root


• Generate random numbers
• Work with dates
• Plot graphs

❌ Writing all logic from scratch → hard + time-consuming


✅ Using libraries → easy + fast + reliable

3. What is the Difference Between Module and Library?

Term Meaning

Module A single Python file (.py) containing code

Library A collection of related modules


Example:

• math → module
• numpy → library (many modules inside)

4. How Python Uses Libraries: (import Concept)

Python does not load all libraries automatically. We must tell Python which
library we want to use.

This is done using import.

Basic syntax:

import library_name

Example:

import math
print([Link](16))

Output: 4.0

Explanation:

• math → library/module
• sqrt() → function inside math
• 16 → input
• 4.0 → result

5. Different Ways to Import Libraries

5.1 Normal Import

import math
print([Link])

Output: 3.141592653589793
Explanation:

• [Link] → value of π
• Library name must be written before function/variable

5.2 Import with Alias (Short Name)

import math as m
print([Link](36))

Output: 6.0

Explanation:

• as m → gives short name to library


• [Link]() → same as [Link]()

5.3 Import Specific Functions

from math import sqrt, pi


print(sqrt(49))
print(pi)

Output:

7.0
3.141592653589793

Explanation:

• No need to write math. every time


• Use function directly
6. Built-in Libraries vs. External Libraries

6.1 Built-in Libraries (Already Installed)

Examples:

• math
• random
• datetime
• sys

*No installation needed.

6.2 External Libraries (Need Installation)

External libraries are Python libraries that are not available by default.
We must install them separately before using them.

They are created by:

• Python community
• Researchers
• Industry developers

Examples:

▪ NumPy – For numerical computations


▪ Pandas – For data manipulation and data analysis
▪ Matplotlib – For data visualization (graphs, charts, plots)
▪ Seaborn – Creating statistical representations of data and visualization
▪ SciPy – For scientific and technical computing
▪ scikit-learn – For machine learning algorithms
▪ TensorFlow – For deep learning and neural networks
▪ Keras – For building and training neural network models
▪ Requests – For making HTTP requests (working with APIs)
▪ BeautifulSoup – For web scraping (extracting data from websites)
▪ Django – For web development (backend web applications)
7. Important Built-in Libraries

7.1 math Library

import math
print([Link](5))

Output: 120

Explanation:

• factorial(5) = 5×4×3×2×1 = 120


• Used for mathematical calculations

7.2 random Library

import random
print([Link](1, 10))

Output (changes every time): 7

Explanation:

• Generates a random number between 1 and 10


• Used in games, simulations, lucky draws

7.3 datetime Library

from datetime import date


today = [Link]()
print(today)

Output (example): 2025-12-17

Explanation:

• Gets today’s date


• Used in attendance, billing, logs
from datetime import date, timedelta
yesterday = [Link]()-timedelta(days=1)
print(yesterday)

Output (example): 2025-12-16

7.4 sys Library

import sys
print([Link])

Output: 3.13.0

Explanation:

• Shows Python version


• Used for system-level programs

8. External Libraries

Why Python Does Not Include Them by Default?

Because:

• Python wants to stay lightweight


• Different users need different tools
• Installing only what we need saves memory

How Do We Install External Libraries?

Tool Used: pip

pip is Python’s package manager.

Installation Command:

pip install library_name

Example:

pip install numpy


Explanation:

• pip → tool
• install → action
• numpy → library name

Checking Installation:

import numpy
print(numpy.__version__)

*If no error → installation successful ✅

8.1 NumPy: (Numerical Computing)

What is NumPy?

NumPy is used for fast mathematical and numerical operations on large data.

Example:

import numpy as np

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


print(arr)

Output: [1 2 3 4]

Explanation:

• array() creates a numeric array


• Faster than Python lists
• Used in scientific computing
How It Works:

Problem Without NumPy:

Suppose we have marks of students: marks = [10, 20, 30, 40]

To add 5 marks to each student:

new_marks = []
for m in marks:
new_marks.append(m + 5)
print(new_marks)

*Long and slow for large data

Same Problem Using NumPy

import numpy as np

marks = [Link]([10, 20, 30, 40])


new_marks = marks + 5
print(new_marks)

Output: [15 25 35 45]

*What happened in the back end?

[10 20 30 40]
+5 +5 +5 +5
-------------
[15 25 35 45]
Problem 1: NumPy Arrays- Data Type, Dimension, Shape & Reshape

# Creating array objects


import numpy as np

# (Instead of writing [Link], we write [Link].)

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

output: arr=[1 2 3]
*It creats a 1-dimensional Numpy array

# Printing the type of array objects


print("Array is of type: ", type(arr))

Output:

Array is of type: <class '[Link]'>

Explanation:

• ndarray = N-dimensional array


• This confirms that arr is a NumPy array, not a Python list

# Printing the type of Data types

import numpy as np

arr = [Link]([10, 20, 30])


print([Link])

Output:int64

Meaning:

• dtype → data type of elements in the array


• Here all values are integers → int64
Another Example (Float)

arr = [Link]([10.5, 20.2, 30.1])


print([Link])

Output: float64

*NumPy stores all elements in an array with the same data type.

Mixed Data Example

arr = [Link]([10, 20.5, 30])


print([Link])

Output: float64

*NumPy upgrades to a common type to avoid data loss.

# Different Dimensions of NumPy Arrays

(a) 1-Dimensional Array (1-D)

a = [Link]([1, 2, 3, 4])
print(a)
print([Link])

Output:

a= [1 2 3 4]

Dimension: 1

*Looks like a list and has only one axis

(b) 2-Dimensional Array (2-D)

b = [Link]([[1, 2, 3],
[4, 5, 6]])
print(b)
print([Link])
Output:

b= [[1 2 3]
[4 5 6]]

Dimension: 2

*Looks like a table (rows × columns)

(c) 3-Dimensional Array (3-D)

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


Print(c)
print([Link])

Output

c= [[[1 2]
[3 4]]

[[5 6]
[7 8]]]

Dimension: 3

# Printing shape of array

Example (1-D)

a = [Link]([1, 2, 3, 4])
print([Link])

Output:(4,)

*4 elements, 1 dimension

Example (2-D)

b = [Link]([[1, 2, 3],
[4, 5, 6]])
print([Link])
Output:(2, 3)

*2 rows, 3 columns

Example (3-D)

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


print([Link])

Output:(2, 2, 2)

*2 layers × 2 rows × 2 columns

# Printing size (total number of elements) of the array

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

print("Size of array: ", [Link])

Output:

Size of array: 6

Explanation:

• size = total number of elements


• Calculation: 2 × 3 = 6

# Reshaping a NumPy Array

What is reshape()?

reshape()is a NumPy method used to change the shape (dimension) of the


array without changing the data.

Key rule: number of elements before = number of elements after

Using reshape(n1,n2,n3,...,nk) NumPy method, one can change the


dimension of NumPy array, such that n1 × n2 × · · · × nk = m.
Example:

import numpy as np
arr = [Link]([1, 2, 3, 4, 5, 6])
print(arr)

Output:[1 2 3 4 5 6]

Reshape into 2 × 3 matrix

new_arr = [Link](2, 3)
print(new_arr)

Output:

[[1 2 3]
[4 5 6]]

*Same elements, different structure

Reshape into 3 × 2 matrix

print([Link](3, 2))

Output:

[[1 2]
[3 4]
[5 6]]

Wrong Reshape (Important Error)

[Link](4, 2)

Error because:

4 × 2 ≠ 6

*Total elements must remain the same.


Automatic Reshape using -1

print([Link](2, -1))

Output:

[[1 2 3]
[4 5 6]]

*NumPy automatically calculates missing values.

Note:
arr = [Link](m) gives an 1D array of m elements 0 to m-1.

Example:

import numpy as np
arr = [Link](0,10).reshape(3,4)

What happens internally?

• [Link](0,10) creates 10 elements

[0 1 2 3 4 5 6 7 8 9]

• .reshape(3,4) requires:

3 × 4 = 12 elements

Output:

ValueError: cannot reshape array of size 10 into


shape (3,4)

Reshape into (1,12) → 2-D Array

arr1 = [Link](0,12).reshape(1,12)
print(arr1)
print([Link])
Output:

[[ 0 1 2 3 4 5 6 7 8 9 10 11]]

(1, 12)

Explanation

• [Link](0,12) → 12 elements
• .reshape(1,12) → 1 row, 12 columns
• This is a 2-D array

Reshape into (2,6) → 2-D Matrix

arr2 = [Link](0,12).reshape(2,6)
print(arr2)
print([Link])

Output:

[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]]

(2, 6)

Explanation

12 elements reshaped into 2 rows × 6 columns

Still a 2-D array, but a different structure, i.e., data remains the same, only the
arrangement changes.

Reshape into (2,3,2) → 3-D Array

arr3 = [Link](0,12).reshape(2,3,2)
print(arr3)
print([Link])
Output:

[[[ 0 1]
[ 2 3]
[ 4 5]]

[[ 6 7]
[ 8 9]
[10 11]]]

(2, 3, 2)

Explanation

12 elements reshaped into a 3-D array

Shape (2,3,2) means:

2 layers
3 rows per layer
2 columns per row

This is a stack of two 2-D matrices

Problem 2: Mean and Standard Deviation using NumPy

# Calculate mean

import numpy as np

# Creating a NumPy array


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

# Calculate mean
mean_val = [Link](data)

print("Mean:", mean_val)

Output:

Mean: 5.0
Meaning: Mean (average) formula

Sum of values / Number of values

Calculation:

(1+2+3+4+5+6+7+8+9) / 9 = 45 / 9 = 5

# Calculating Variance using NumPy

import numpy as np

# Creating a NumPy array


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

# Calculate variance
variance = [Link](data)

# Printing variance
print("Variance:", variance)

Output:

Variance: 6.666666666666667

Meaning: Variance is a statistical measure that indicates how much the data
values differ from the mean value of the dataset.

In other words, variance tells us how widely the data is spread around the
average.

• If the variance is small, the data values are close to the mean.
• If the variance is large, the data values are far away from the mean.

Variance =(1/n)∑(xi−mean)2

# Calculate standard deviation

std_dev = [Link](data)

print("Standard deviation:", std_dev)


Output:
Standard deviation: 2.58198

Meaning: Standard deviation is the square root of variance.

Standard Deviation= sqrt{Variance}

# Calculate Median

import numpy as np
data = [Link]([1, 2, 3, 4, 5, 6, 7, 8, 9])
median_val = [Link](data)
print("Median:", median_val)

Output:

Median: 5.0

Rule:

The data is already in sorted order:

1, 2, 3, 4, 5, 6, 7, 8, 9

• Total number of values = 9 (odd)


• Middle position = (9+1)/2=5(9 + 1) / 2 = 5(9+1)/2=5

5th value = 5

Meaning: Median is the middle value of a dataset when the data is arranged in
ascending or descending order.

• If the number of values is odd → median is the middle value


• If the number of values is even → median is the average of the two
middle values
Problem 3: Basic Statistical Operations in NumPy (max, min, sum)

One can find the maximum from the numpy array using the max() method, the
minimum using the min() method, and the sum using the sum() method.

Example:

import numpy as np
test_scores = [70, 65, 95, 88]
scores = [Link](test_scores)

Explanation

• test_scores → Python list


• [Link]() → converts list into a NumPy array
• NumPy arrays allow fast mathematical operations

Finding the Maximum Value — max()— returns the largest value in the
array

[Link]()

Output: 95

Finding the Minimum Value — min()— returns the smallest value in the
array

[Link]()

Output: 65

Finding the Sum of Values — sum()

[Link]()

Output: 318
Problem 4: Matrix Operations in Python Using NumPy

What is a Matrix?

A matrix is a rectangular arrangement of numbers in rows and columns.

Example:

| 1 2 |
| 3 4 |

In NumPy, matrices are represented as 2-D arrays.

Creating a Matrix in NumPy

import numpy as np

A = [Link]([[1, 2],
[3, 4]])

Output:

[[1 2]
[3 4]]

Visualization:

A =
| 1 2 |
| 3 4 |

Matrix Addition

Rule:

• Same number of rows and columns


• Add corresponding elements
Example:

B = [Link]([[5, 6],
[7, 8]])

C = A + B
print(C)

Output:

| 6 8 |
| 10 12|

Calculation:

1+5 2+6
3+7 4+8

Matrix Subtraction

C = B - A
print(C)

Output:

| 4 4 |
| 4 4 |

Scalar Multiplication

Multiply the matrix by a number

C = 3 * A
print(C)

Output:

| 3 6 |
| 9 12 |

Each element multiplied by 3.


Element-wise Multiplication

C = A * B
print(C)

Output:

| 5 12 |
| 21 32 |

• This is NOT matrix multiplication.


• It multiplies element by element

Matrix Multiplication (Dot Product)

Mathematical rule:

(2×2) × (2×2) → possible

Using dot() or @

C = [Link](A, B)
print(C)

or

C = A @ B
print(C)

Output:

| 19 22 |
| 43 50 |

Calculation:

(1×5 + 2×7) (1×6 + 2×8)


(3×5 + 4×7) (3×6 + 4×8)
Transpose of a Matrix

Rows become columns and vice versa

AT = A.T
print(AT)

Output:

| 1 3 |
| 2 4 |

Problem 5: Linear Algebra using NumPy

import numpy as np
import [Link] as LA

Explanation:

• [Link] → module for linear algebra


• as LA → alias

A = [Link]([[1, 2], [3, 4]])

Matrix form:

| 1 2 |
| 3 4 |

Determinant:

print([Link](A))

Output: -2.0
Explanation:

Determinant formula for 2×2 matrix

|a b|
|c d| = ad − bc

Calculation:(1×4) − (2×3) = 4 − 6 = −2

Inverse of Matrix:

print([Link](A))

Output:

[[-2.0 1.0]
[ 1.5 -0.5]]

Meaning:

Inverse matrix satisfies: A × A⁻¹ = Identity matrix

Identity Matrix

I = [Link](2)
print(I)

Output:

| 1 0 |
| 0 1 |

Eigenvalues and Eigenvectors:

eigenvalues, eigenvectors = [Link](A)

print("Eigenvalues:\n", eigenvalues)

print("Eigenvectors:\n", eigenvectors)
Types of questions related to NumPy:

1. What is NumPy? Why is it faster than Python lists?

2. Define ndarray. What are its advantages?

3. Difference between:

a. Python list and NumPy array


b. array() vs arange()
c. reshape() and resize()

4. What is broadcasting in NumPy?

5. Write syntax to:

a. Create a NumPy array


b. Find the shape and dimension of an array
c. Generate zeros / ones matrix
d. Find max, min, mean of an array

6. What will be the output of the following?

import numpy as np
a = [Link]([1, 2, 3])
print(a * 2)

7. Programming Questions

a. Create a 3×3 matrix and find its transpose


b. Find the sum of all elements in an array
c. Extract even numbers from an array
d. Perform element-wise addition of two arrays

Note:
Cover all related questions in Assignment 6.
8.2 Pandas Library in Python

🔹What is Pandas?

Pandas is used for handling, analyzing, and manipulating data in tabular form
(rows & columns), similar to Excel sheets.

It provides powerful data structures such as Series and DataFrame, which are
designed for handling large and structured datasets.

• A Series is a one-dimensional labelled array capable of holding data of any


type.

• A DataFrame is a two-dimensional table-like structure with labelled rows


and columns.

Pandas is widely used for data preprocessing, including filtering, reshaping,


merging, and aggregation of data.

It is best for:

• Student records, marks, attendance, Excel data

🔹 How to Install Pandas

(Outside Python, in Command Prompt)

pip install pandas

🔹 How to Use/Import Pandas

import pandas as pd

Example:

1. Creating a Pandas Series

import pandas as pd

data = [10, 20, 30, 40, 50]


s = [Link](data)
print(s)
Output:

0 10
1 20
2 30
3 40
4 50

Explanation:

• A Series is a one-dimensional labelled array


• Left side → Index
• Right side → Values

*Pandas automatically assigns an index starting from 0

➢ Series with Custom Index

import pandas as pd
data=[10, 20, 30]
index=["a", "b", "c"])

s = [Link](data,index=index)
print(s)

Output:

a 10
b 20
c 30
dtype: int64

➢ Accessing Series Properties

❖ print("Values:", [Link])

Output:

Values: [10 20 30]

*Returns only the data values (without index)


❖ print("Index:", [Link])

Output:

Index: Index(['a', 'b', 'c'], dtype='object')

*Returns index labels

❖ print("Size:", [Link])

Output:

Size: 3

*Returns total number of elements

❖ print("Ndim:", [Link])

Output:

Ndim: 1

*The series is 1-dimensional

❖ print("Shape:", [Link])

Output:

Shape: (3,)

Means:

• 3 elements
• One dimension
2. Creating a Data Frame

(a)
data = {
"Name": ["Amit", "Rita", "Suman"],
"Marks": [78, 85, 90]
}

df = [Link](data)
print(df)

Output:

Name Marks
0 Amit 78
1 Rita 85
2 Suman 90

Explanation:

• A DataFrame is a 2-dimensional table


• Similar to an Excel sheet
• Each column has a name
• Each row has an index
• Easy to read, analyze, and modify data
• Used for storing structured data.

(b)
data = {
'Name': ['A', 'B', 'C'],
'Age': [25, 30, 35],
'City': ['BBS', 'RKL', 'KOL']
}

df = [Link](data)
print(df)

Output:

Name Age City


0 A 25 BBS
1 B 30 RKL
2 C 35 KOL
(c)
df = [Link]({
"Name": ["AA", "BB", "CC"],
"Age": [24, 30, 29],
"Salary": [50000, 60000, 70000]
})

print(df)

Output:

Name Age Salary


0 AA 24 50000
1 BB 30 60000
2 CC 29 70000

Basic Pandas Functions


import pandas as pd
df = [Link]({
"Name": ["Amit", "Riya", "John"],
"Age": [21, 22, 19],
"Score": [88,92,75]
})

1. [Link]()→ Displays the first few rows of the DataFrame.

Name Age Score


0 Amit 21 88
1 Riya 22 92
2 John 19 75

2. [Link]()→ Displays the last few rows of the DataFrame.

Name Age Score


0 Amit 21 88
1 Riya 22 92
2 John 19 75
3. [Link]() → Shows summary information like column
names, datatypes, and non-null count.

<class '[Link]'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):

# Column Non-Null Count Dtype


--- ------ -------------- -----
0 Name 3 non-null object
1 Age 3 non-null int64
2 Score 3 non-null int64
dtypes: int64(2), object(1)
memory usage: 200+ bytes

4. [Link]() → Gives statistical details of


numerical columns.

Age Score
count 3.000000 3.000000
mean 20.666667 85.000000
std 1.527525 8.888194
min 19.000000 75.000000
25% 20.000000 81.500000
50% 21.000000 88.000000
75% 21.500000 90.000000
max 22.000000 92.000000

5. [Link] → Returns number of rows and columns.

(3, 3)

➡️ 3 rows, 3 columns

6. [Link] → Displays column names.


Index(['Name', 'Age', 'Score'], dtype='object')
7. [Link] → Shows data type of each column.

Name object
Age int64
Score int64
dtype: object

Specific Operation on DataFrame

df = [Link]({
"Name": ["AA", "BB", "CC"],
"Age": [24, 30, 29],
"Salary": [50000, 60000, 70000]
})

print(df)

1. Selecting a Single Column

print(df["Age"])

Output:

0 24
1 30
2 29
Name: Age, dtype: int64

*Output is a Series

2. Selecting Multiple Columns

print(df[["Name", "Salary"]])

Output:

Name Salary
0 AA 50000
1 BB 60000
2 CC 70000

*Output is a DataFrame
3. Selecting Rows using loc (Label-based indexing)

print([Link][0:1])

Output:

Name Age Salary


0 AA 24 50000
1 BB 30 60000

• loc is label-based indexing


• Both start and end labels are INCLUDED
• So rows with index 0 and 1 are printed

Rule:

loc[start : end] → end is included

[Link][row_label, column_label]

4. Selecting Rows using iloc (Position-based/ Integer


Location-based Indexing)

print([Link][0:2])

Output:

Name Age Salary


0 AA 24 50000
1 BB 30 60000

• iloc is position-based indexing


• End position is EXCLUDED
• Positions 0 and 1 are selected (2 is excluded)

Rule:

iloc[start : end] → end is excluded


#[Link][row_position, column_position]
How to CHANGE / MODIFY Data in Pandas

1. Change a Single Value (Using loc)

Example: Change Age of BB from 30 to 32

[Link][1, "Age"] = 32
print(df)

Meaning:

• Row label = 1
• Column = "Age"
• New value = 32

2. Change Using iloc (Position-based)

Example: Change Salary of first row

[Link][0, 2] = 52000
print(df)

Meaning:

• Row position = 0
• Column position = 2 (Salary)

3. Change an Entire Column

Example: Increase all salaries by 10%

df["Salary"] = df["Salary"] * 1.10


print(df)

4. Update Multiple Columns Together

[Link][0:, ["Age", "Salary"]] = df[["Age", "Salary"]]


+ 1
5. Change Values Using Condition (Very Important)

Example: Filtering data

Increase salary where Age > 25

[Link][df["Age"] > 25, "Salary"] = df["Salary"] + 5000


print(df)

when salary > 55000


print(df[df["Salary"] > 55000])

Output:

Name Age Salary


1 BB 30 60000
2 CC 29 70000

*Only rows where salary > 55000 are displayed

6. Add a New Column

df["Tax"] = df["Salary"] * 0.1


print(df)

7. Rename Column

[Link](columns={"Salary": "Monthly_Salary"},
inplace=True)
print(df)
Reading a CSV File using Pandas

Given Code:

import pandas as pd
import os

# Let Python know correct directory for file.

[Link]('C:\\Users\\...\\Program Files\\Chapter 12')


print('Current directory', [Link]())

Explanation:
Importing Required Libraries:

1. import pandas as pd

• Imports Pandas library


• Used for data manipulation and analysis
• pd is an alias (short name)

Used later for:

• Reading CSV files


• Handling tables (DataFrame)

2. import os

• Imports the Operating System (OS) module


• Used to interact with:
o Files
o Folders
o Directories

Very important when working with CSV files stored in folders.

3. Changing the Working Directory

[Link]('C:\\Users\\...\\Program Files\\Chapter 12')


Meaning:

• chdir → change directory


• Tells Python: “Look for files in this folder”

➢ This is done so Python can find the CSV file without giving the full path
every time.

4. Checking Current Working Directory

print('Current directory', [Link]())

Meaning:

• getcwd() → get current working directory


• Prints the folder where Python is currently looking for files

Why is this code important?

This code is used when:

• CSV file is stored in a specific folder


• Python cannot find the file by default

Instead of writing:

pd.read_csv("C:\\Users\\...\\Program Files\\Chapter
12\\[Link]")

We can simply write:

pd.read_csv("[Link]")

Note: The [Link]() function is used to set the working directory so that
Python can easily access files stored in a specific folder.
Example:

#Method 1

import pandas as pd
import os

# Change directory
[Link]("E:\\Python")
print("Current Directory:", [Link]())

# Read CSV
df = pd.read_csv("student_data.csv")
print(df)

# Method 2: Direct File Path

#Read CSV
import pandas as pd

df_csv = pd.read_csv("E:\\Python\\student_data.csv")
print(df)

#Read Excel

Df_excel =
pd.read_excel("E:\\Python\\student_data.xlsx")
print(df)

Note: After reading the file, we obtain a DataFrame.


All standard operations can then be performed on this
DataFrame, and many built-in functions such as max(),
min(), and sum() also work wherever applicable, similar
to NumPy.
Types of questions related to Pandas:

1. What is Pandas?
2. Difference between Series and DataFrame.
3. What is a DataFrame index?
4. What are missing values? How are they handled in Pandas?
5. Write commands to:
a. Read a CSV file
b. Display first 5 rows
c. Select a column
d. Select multiple columns
e. Use loc and iloc
f. Check shape and info of DataFrame

6. Write the output of the following

import pandas as pd
df = [Link]({"A":[1,2], "B":[3,4]})
print(df["A"])

7. Programming / Data Handling


a. Create a DataFrame from dictionary
b. Add a new column
c. Filter rows based on condition
d. Find average of a column

Note:
Cover all related questions in Assignment 6.
8.3 Matplotlib Library in Python

What is Matplotlib?

Matplotlib is a powerful Python plotting library used to visualize data in


graphical form.

It supports many types of plots such as line plots, scatter plots, bar charts, and
histograms, and allows full customization of colors, labels, titles, legends, and more.

Why Visualization is Important

Consider this data:

50, 60, 70, 80

• As numbers → hard to see trend


• As a graph → trend becomes clear instantly

*Matplotlib converts numbers into visual meaning.

Importing Matplotlib

import [Link] as plt

• pyplot → plotting module


• plt → alias (short name)

1. Line Graph

Example 1:

import [Link] as plt

x = [1, 2, 3, 4]
y = [1, 4, 9, 16]

[Link](x, y)
[Link]("X values")
[Link]("Y values")
[Link]("Line Plot")
[Link]()
*Without [Link](), graph will not appear.

Example 2:
import [Link] as plt

[Link]([0, 4, 5], [4, 5, 6])


[Link]("X axis")
[Link]("Y axis")
[Link]("Line Plot")
[Link]()
*Note:

[Link]() — Line Graph

Purpose: Draws a line plot between x and y values.

[Link]() — Display the Graph

Purpose: Displays the graph on the screen.

[Link]() — Label X-axis

Purpose: Gives a name to the x-axis.

[Link]() — Label Y-axis

Purpose: Gives a name to the y-axis.

[Link]() — Title of the Graph

Purpose: Adds a heading to the graph.

[Link]() — Show Legend

Purpose: Displays labels for multiple lines.

2. Bar Chart

[Link]()

Purpose: Draws a bar chart (comparison).

import [Link] as plt


names = ["A", "B", "C"]
marks = [70, 85, 90]

[Link](names, marks)
[Link]()

Used for:

• Comparing categories
• Results, surveys
3. Scatter Plot
[Link]()

Purpose: Shows relationship between two variables using dots.

import [Link] as plt


Rollno = [1,2,3,4,5,6,7,8,9,10]
marks = [70, 85, 90,50,64,87,93,12,45,67]

[Link](Rollno, marks)
[Link]("Roll No")
[Link]("Marks")
[Link]("Roll. No Vs. Marks")
[Link]()

Used for:

• Statistics
• Machine learning
• Correlation study
4. Histogram

[Link]()

Purpose: Shows the distribution of data.

import [Link] as plt


data = [10, 20, 20, 30, 40, 40, 50]
[Link](data)
[Link]()

Used for:

• Frequency analysis
• Spread of data
#Complete Program Example:

import [Link] as plt

# Data
students = [1, 2, 3, 4, 5]
marks = [65, 70, 75, 85, 90]

# Plotting
[Link](students, marks, label="Marks")
[Link]("Students")
[Link]("Marks")
[Link]("Result Analysis")
[Link]()
[Link](True)
[Link]()
Types of questions related to Matplotlib:

1. What is Matplotlib?
2. What is pyplot?
3. Purpose of:
o xlabel(), ylabel()
o title()
o legend()
o grid()

4. Write syntax to:

o Plot a line graph


o Plot a bar chart
o Plot a scatter plot
o Display a graph

5. Write a Python program to plot a graph showing students vs marks.


6. Identify Errors / Missing Lines
• Find missing statement to display graph
• Correct the plotting code

7. Combined / Mixed Questions

• Read data using Pandas and plot it using Matplotlib


• Create NumPy array → convert to DataFrame → plot values
• Given a dataset, perform:
o Data loading
o Data selection
o Data visualization
8.4 Seaborn Library in Python

What is Seaborn?

Seaborn is a Python data visualization library used to create attractive and


informative statistical graphs.

It is built on top of Matplotlib and works especially well with Pandas


DataFrames.

Why Seaborn is Used

• Provides better-looking plots with less code


• Ideal for statistical data visualization
• Automatically handles:
o Mean
o Confidence interval
o Grouping of data
• Easy to use with real-world datasets

Relationship with Matplotlib

Seaborn uses Matplotlib internally commands like:

• [Link]()
• [Link]()
• [Link]()
• [Link]()

are still Matplotlib commands, even when plotting with Seaborn.

Importing Seaborn

import seaborn as sns


import [Link] as plt
Common Seaborn Plot Commands

Plot Type Seaborn Command

Line plot [Link]()

Bar plot [Link]()

Scatter plot [Link]()

Histogram [Link]()

Box plot [Link]()

Count plot [Link]()

Heatmap [Link]()

Example: Line Plot using Seaborn

import seaborn as sns


import [Link] as plt

x = [1, 2, 3, 4]
y = [10, 20, 30, 40]

[Link](x=x, y=y)
[Link]("Line Plot using Seaborn")
[Link]()

Working with Pandas DataFrame

[Link](x="Name", y="Marks", data=df)

✔ Directly uses column names


✔ No need to extract lists manually
Advantages of Seaborn

• Less code required


• Better default styles
• Strong support for statistical plots
• Easy integration with Pandas
• Built-in themes and color palettes

Limitations of Seaborn

• Less low-level control than Matplotlib


• Depends on Matplotlib
• Not ideal for very basic plots in exams

When to Use Seaborn

• When data is in Pandas DataFrame


• When statistical analysis is required
• When visual appearance matters

Types of questions related to Seaborn

1. What is Seaborn?
2. Is Seaborn built on top of Matplotlib?
3. Which type of data works best with Seaborn?
4. Write the import statement for Seaborn.
5. Name any one statistical plot available in Seaborn.
6. Write the difference between Seaborn and Matplotlib (any two points).
7. What is the purpose of [Link]()?
8. Name any four plot functions available in Seaborn.
9. Why is Seaborn preferred over Matplotlib for statistical visualization?
[Link] Seaborn work with Pandas DataFrames? Explain briefly.
[Link] how Seaborn simplifies data visualization.
[Link] between [Link]() and [Link]().
8.5 SciPy Library in Python

What is SciPy?

SciPy (Scientific Python) is a Python library used for scientific and


mathematical computations.

It is built on top of NumPy and provides advanced functions for mathematics,


science, and engineering.

Why SciPy is Used

• Provides advanced mathematical functions


• Efficient for scientific calculations
• Used in engineering, physics, data science
• Works with NumPy arrays

Relationship with NumPy

• SciPy depends on NumPy


• NumPy → basic array operations
• SciPy → advanced scientific operations

Importing SciPy

import scipy

Or specific modules:

from scipy import linalg, integrate, stats

Important SciPy Modules

Module Purpose
[Link] Linear algebra
[Link] Interpolation
[Link] Integration
[Link] Optimization
[Link] Statistics
[Link] Signal processing
Example: Linear Algebra

from scipy import linalg


import numpy as np

a = [Link]([[1, 2], [3, 4]])


det = [Link](a)
print(det)

Advantages of SciPy

• Faster computations
• Large collection of scientific functions
• Easy integration with NumPy
• Reliable and well-tested

Limitations of SciPy

• Not meant for visualization


• Requires knowledge of NumPy
• Not used for machine learning directly
8.6 Scikit-learn Library in Python

What is Scikit-learn?

Scikit-learn is a Python library used for machine learning.

It provides simple tools for classification, regression, clustering, and model


evaluation.

Why Scikit-learn is Used

• Easy to implement machine learning algorithms


• Beginner-friendly
• Works well with NumPy and Pandas
• Widely used in data science

Importing Scikit-learn

import sklearn

Example:

from sklearn.linear_model import LinearRegression

Major Components of Scikit-learn

Component Purpose
Supervised learning Classification, Regression
Unsupervised learning Clustering
Model selection Train-test split
Preprocessing Scaling, encoding
Metrics Accuracy, error calculation
Example: Simple Linear Regression

from sklearn.linear_model import LinearRegression


import numpy as np

X = [Link]([[1], [2], [3], [4]])


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

model = LinearRegression()
[Link](X, y)

print([Link]([[5]]))

Advantages of Scikit-learn

• Simple syntax
• Many built-in algorithms
• Good documentation
• Ideal for beginners

Limitations of Scikit-learn

• Not suitable for deep learning


• Works mainly with structured data
• Less flexible than advanced ML libraries

You might also like