0% found this document useful (0 votes)
9 views34 pages

Project

Uploaded by

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

Project

Uploaded by

Ayesha Nagma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Python Fundamentals

beginners course
Ambala College of Engineering & Applied Research

A Training Report
Submitted in the partial fulfilment of requirement for the award
of the degree of

Bachelor of Technology
(Computer Science and Engineering)

Submitted to
Ambala College of Engineering & Applied Research

Devsthali, Ambala (Haryana)

From July 16, 2024 to August 9, 2024


Submitted By: Ayesha
Roll no: 2323007

Department of Computer Science and Engineering


Ambala College of Engineering and Applied Research
(Affiliated to Kurukshetra University, Kurukshetra)

i
Student Declaration

I, Ayesha, Roll No 2323007, hereby declare that the work done by me on “Python
Fundamentals beginners course” from July,2024 to August, 2024, is a record of
original work for the partial fulfillment of the requirements for the award of the degree,
Bachelor of Technology(Computer Science & Engineering).

Student Name: Ayesha, 2323007

Signature of the student

Dated:

ii
Declaration by the supervisors

This is to certify that Ayesha, 2323007 from Ambala College of Engineering & Applied
Research, Devsthali, Ambala, has worked as a trainee in Ambala College of Engineering
& Applied Research on “Python Fundamentals beginners course” under my
supervision from July, 2024 to August, 2024. It is further stated that the work carried out
by the student is a record of original work to the best of my knowledge for the partial
fulfillment of the requirements of the award of the degree Bachelor of
Technology(Computer Science & Engineering).

Name of External Supervisor:


Er. Semma Rani (Co-Ordinator (CSE)) &
Er. DikshaSaini(Assistant Professor)

Signature of the external Supervisor:

Dated:

iii
certificate

iv
Acknowledgement

I would like to place on record with my deep sense of gratitude to my training instructor Er.
Seema Rani and Er. Diksha for the stimulating guidance, continuous encouragement and
supervision for the submission of the training report and presentation. Thank you so much for
all of the academic, professional and personal advice that you have given me. The completion
of this training would not have been possible without the boundless encouragement and
support of my family. From you all, I have learned to take pride in my work and to enjoy the
simple pleasure of a job well done.

Thank you for everything that you have given me.

Ayesha
(2323007)

v
Table of Contents

CHAPTER TOPIC PAGE NO.

1. Introduction to the 7-8


Company/Institute.

2. Introduction to Python 9-26

3. Introduction to Seaborn 27-31

4. Introduction to Numpy 32-34

5. Introduction to Pandas 35-38

6. Introduction to Matplotlib 39-43

7. Project Documentation and 44-61


Implementation

8. Conclusion 62

9. References 63

vi
Chapter – 01
Introduction to the Company/ Institute

1.1 Introduction:
Ambala College of Engineering and Applied Research (ACE) stands out as a
leading institution dedicated to shaping the future of engineering and
technology. Here are some key highlights that make ACE a premier choice for
aspiring engineers

Ambala College of Engineering and Applied Research is renowned for its


rigorous academic programs and high standards of education. The college
offers a variety of undergraduate and postgraduate courses in engineering and
applied research, ensuring that students receive a comprehensive and up-to-
date education.

1.2 Services Offered:


Research and Innovation
The institution emphasizes research and innovation, encouraging students to
engage in cutting-edge projects and research initiatives. This focus on research
helps foster a culture of inquiry and creativity, preparing students to contribute
to technological advancements.

Industry Collaboration
Ambala College of Engineering and Applied Research maintains strong ties
with the industry, facilitating internships, training programs, and placement
opportunities for students. These collaborations ensure that students gain
practical experience and are well-prepared for the professional world.

Holistic Development
The college places a strong emphasis on the holistic development of students.
In addition to academic pursuits, Ambala College of Engineering and Applied
Research offers a variety of extracurricular activities, including sports, cultural

7
events, and technical clubs. These activities help students develop leadership
skills, teamwork, and a well-rounded personality.
1.3 Purpose of Internship/Training:

Internship/Training program provides a new perspective to the students. It


provides learning opportunities outside the boundaries of the course
curriculum and classroom activities. These opportunities enhance student’s
capability to apply theoretical understanding into real-world scenarios, thereby
enhancing the students’ academic and career goals.
From the student perspective, internship/training assists with career
development in different diverse fields such as coding, programming,
networking, marketing, etc. by providing vital work experience that allows
students to explore their area of interests and develop relevant skills and
competencies.
From the organization perspective, internship/training provides a unique
opportunity to train fresh talents, enhance their professional development as
well as aid the professional growth of the intern/trainee mentors/supervisor.
Organization can also find potential employees within the interns/trainee.

1.4 Objective of Internship/Training:


The major objectives of internships/trainings are:
To provide students with opportunity to develop skills in the field of interest
To assist students in gaining vital work-related experience and building strong
resume for bright career.
To help students in developing business contacts i.e. creating network
contacts.
To expose students to a particular job and a profession or industry.
To help students potentially land permanent or contractual jobs from host
company standard projects.

8
Chapter – 02
Introduction to Python

2.1 Introduction:
Python is a versatile and widely-used programming language renowned for its
simplicity, readability, and extensive range of libraries and frameworks. It was
created by Guido van Rossum and first released in 1991. Python's popularity
has grown exponentially, making it a top choice for various applications
including web development, data analysis, artificial intelligence, scientific
computing, automation, and more.

One of Python's key strengths lies in its elegant syntax, which emphasizes
human-readable code. This characteristic not only accelerates development but
also encourages collaboration among developers. Python's dynamic typing
system allows variables to change data types during runtime, enhancing
flexibility but requiring careful attention to type-related errors.

Python's expansive standard library offers numerous built-in modules and


functions, providing ready-to-use tools for tasks such as file manipulation,
networking, data serialization, and regular expressions. Additionally, Python's
Package Index (PyPI) hosts a vast collection of third-party packages that cater
to specialized domains and needs.

For data science and analytics, Python's libraries like NumPy, Pandas, and
Matplotlib provide essential tools for efficient numerical operations, data
manipulation, and data visualization. For machine learning and artificial
intelligence, libraries like TensorFlow, PyTorch, and Scikit-learn offer robust
frameworks to build and train models.

Web development is another area where Python excels. Frameworks like


Django and Flask streamline the creation of web applications by providing
9
tools for routing, database integration, authentication, and more. These
frameworks follow the Model-View-Controller (MVC) architecture, fostering
organized and maintainable codebases.

Python's community-driven development and open-source nature contribute to


its continual growth and improvement. Developers worldwide contribute to its
development, ensuring regular updates, bug fixes, and the creation of new
features. Online resources, forums, and tutorials abound, facilitating the
learning process and problem-solving for newcomers and experienced
developers alike.

In conclusion, Python's simplicity, versatility, and extensive ecosystem make it


an ideal choice for various programming tasks. Its ease of use, coupled with its
robust libraries and frameworks, empowers developers to tackle diverse
challenges with efficiency and effectiveness.

2.2 Installing Python:

 Download Python Installer:


Visit the official Python website at https://www.python.org/downloads/.

 Select Version:
Choose the version of Python you want to install. As of my knowledge cutoff
in September 2021, Python 3 is recommended as Python 2 is no longer
supported.

 Download Installer:
Click on the download link for the version you've chosen. Choose the
appropriate installer for your operating system (Windows, macOS, or Linux).

 Run Installer:
Locate the downloaded installer file and run it.

 Customize Installation (Optional):


10
During installation, you can customize various settings like installation
location, adding Python to PATH, and optional features. Adding Python to
PATH is recommended, as it allows you to run Python from any command
prompt or terminal.

 Complete Installation:
Follow the installation prompts, and the installer will set up Python on your
system.

 Verifying Installation:
Open Command Prompt or Terminal:
On Windows, press Win + R, type cmd, and press Enter. On macOS and
Linux, search for "Terminal" in your applications.

Check Python Version:


 In the command prompt or terminal, type: python --version
 This command will display the installed Python version.

Installing Python Packages:

Python comes with a package manager called "pip" that allows you to easily
install additional packages or libraries. After installing Python, you can use pip
to install packages. For example, to install a package named "numpy," you
would run:
pip install numpy

Remember that package management and best practices might evolve over
time, so it's a good idea to refer to the official Python documentation or other
reliable sources for the most up-to-date information.

2.3 Python Variables:


In Python, variables are used to store and manage data values. They act as
placeholders for different types of information, such as numbers, strings, lists,

11
and more. Variables provide a way to reference data by a name, making it
easier to manipulate and work with values in your programs.

Variable Naming Rules:

Naming Convention: Variable names can consist of letters (both uppercase and
lowercase), digits, and underscores. They must start with a letter or
underscore, followed by any combination of characters.

Case Sensitivity: Python is case-sensitive, meaning myVariable and


myvariable are considered different variables.

Reserved Words: Avoid using reserved words (also known as keywords) like
if, else, while, etc., as variable names, as they have special meanings in
Python.

Assigning Values to Variables:

To assign a value to a variable, you use the assignment operator =. For


example:
age = 25
name = "Alice"

Variable Reassignment:
You can change the value of a variable after it has been assigned:
age = 25
age = 30 # Reassigning the value

Multiple Assignment:
You can assign multiple variables in a single line:

12
x, y, z = 10, 20, 30

Variable Scope:
The scope of a variable refers to where it can be accessed in your code.
Variables can have local scope (within a function) or global scope (accessible
throughout the entire program).

2.4 Constants:
While Python doesn't have true constants, conventionally, constants are named
in uppercase and not meant to be changed:
PI = 3.14

2.5 Strings in python:


Strings are sequences of characters, such as letters, numbers, and symbols,
enclosed within either single (' ') or double (" ") quotes. They are a
fundamental data type in Python and are used to represent textual data.

Creating Strings:
You can create strings by enclosing text within single or double quotes:
name = "Alice"
message = 'Hello, world!'

String Concatenation:
You can combine strings using the + operator:
greeting = "Hello"
name = "Alice"
full_greeting = greeting + " " + name

String Length:
You can find the length of a string using the built-in len() function:
text = "Hello, world!"
length = len(text) # Returns 13

Accessing Characters:
13
Individual characters in a string can be accessed using indexing, where the
index starts from 0:
word = "Python"
first_letter = word[0] # Returns 'P'

Slicing:
You can extract a portion of a string using slicing:
text = "Hello, world!"
substring = text[0:5] # Returns "Hello"

String Methods:
Python provides numerous built-in methods to manipulate and work with
strings:

 lower(): Converts the string to lowercase.


 upper(): Converts the string to uppercase.
 strip(): Removes leading and trailing whitespace.
 replace(old, new): Replaces occurrences of a substring.
 split(delimiter): Splits the string into a list based on the delimiter.
 join(iterable): Joins a list of strings using the given string as a separator.

String Formatting:
Python offers several ways to format strings:
 f-strings: Allow you to embed expressions inside string literals for dynamic
formatting.
 .format(): A method to format strings by substituting placeholders with
values.
 % operator: A legacy way of string formatting.

String Escaping:

If you need to include special characters within a string, you can use escape
sequences, such as \" for double quote and \' for single quote.

Multiline Strings:
14
Triple-quoted strings (''' or """) allow you to create multiline strings:
multiline_text = """
This is a multiline
string in Python.
"""

String Immutability:
Strings are immutable, meaning once they are created, their contents cannot be
changed. However, you can create new strings based on existing ones.

2.6 Operators in Python

Operators are symbols that perform operations on one or more operands


(values). They are essential for performing mathematical computations,
comparisons, logical operations, and more in programming.

Arithmetic Operators:
Arithmetic operators perform basic mathematical operations:
 +: Addition
 -: Subtraction
 *: Multiplication
 /: Division
 %: Modulo (remainder)
 **: Exponentiation (power)
 //: Floor Division (result is the quotient without the decimal part)

Comparison Operators:
Comparison operators compare values and return a Boolean result (True or
False):
 ==: Equal to
 !=: Not equal to
 <: Less than
 >: Greater than
 <=: Less than or equal to
15
 >=: Greater than or equal to
Logical Operators:
Logical operators are used to combine Boolean values or expressions:
 and: Logical AND (returns True if both operands are True)
 or: Logical OR (returns True if at least one operand is True)
 not: Logical NOT (returns the opposite Boolean value)

Assignment Operators:
Assignment operators are used to assign values to variables:
 =: Assign value
 +=: Add and assign
 -=: Subtract and assign
 *=: Multiply and assign
 /=: Divide and assign
 %=: Modulo and assign
 **=: Exponentiate and assign
 //=: Floor divide and assign

Identity Operators:
Identity operators compare the memory addresses of two objects:
 is: Returns True if both operands refer to the same object
 is not: Returns True if both operands refer to different objects

Membership Operators:
Membership operators check if a value is present in a sequence (e.g., string,
list, tuple):
 in: Returns True if the value is in the sequence
 not in: Returns True if the value is not in the sequence

Bitwise Operators:
Bitwise operators perform operations on the binary representations of integers:
 &: Bitwise AND
 |: Bitwise OR
 ^: Bitwise XOR
 ~: Bitwise NOT
16
 <<: Left shift
 >>: Right shift

Operator Precedence:

Operators have precedence levels that determine the order in which operations
are performed. Parentheses can be used to control the order explicitly.

2.7 Data Types:

Python is dynamically typed, which means you don't need to explicitly declare
a variable's type. Python determines the data type based on the assigned value.
Common data types include:

 int: Integer (e.g., age = 25)


 float: Floating-point number (e.g., pi = 3.14)
 str: String (e.g., name = "Alice")
 bool: Boolean (e.g., is_valid = True)

2.71 List
Lists are one of the most versatile and commonly used data structures in
Python. They are used to store collections of items, which can be of different
data types, including numbers, strings, and even other lists.

Creating Lists:
Lists are created by enclosing items in square brackets [ ], separated by
commas:
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "orange"]
mixed_list = [42, "hello", 3.14, True]

Accessing List Items:


List items can be accessed using zero-based indexing:
17
fruits = ["apple", "banana", "orange"]
first_fruit = fruits[0] # "apple"
second_fruit = fruits[1] # "banana"

Modifying List Items:


Lists are mutable, meaning you can change their content after creation:
numbers = [1, 2, 3, 4, 5]
numbers[2] = 7 # Modifies the third element to 7

List Methods:
Python provides a variety of built-in methods to manipulate lists:
 append(item): Adds an item to the end of the list.
 insert(index, item): Inserts an item at a specific index.
 remove(item): Removes the first occurrence of the specified item.
 pop(index): Removes and returns the item at the specified index.
 len(list): Returns the number of items in the list.
 sort(): Sorts the items in ascending order.
 reverse(): Reverses the order of items.

List Slicing:
You can extract a portion of a list using slicing:
numbers = [1, 2, 3, 4, 5]
subset = numbers[1:4] # [2, 3, 4]

List Concatenation:
Lists can be concatenated using the + operator:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2 # [1, 2, 3, 4, 5, 6]

Nested Lists:
Lists can contain other lists as elements, creating nested lists:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

List Comprehensions:
18
List comprehensions provide a concise way to create lists based on existing
lists:
squares = [x ** 2 for x in range(10)]

2.72 Tuple
Tuples are another fundamental data structure in Python that allow you to store
a collection of items. Similar to lists, tuples can hold multiple values, but they
have a few key differences.

Creating Tuples:
Tuples are created by enclosing items in parentheses (), separated by commas:
point = (3, 5)
colors = ("red", "green", "blue")
mixed_tuple = (42, "hello", 3.14)

Accessing Tuple Items:


Tuple items can be accessed using zero-based indexing, similar to lists:
point = (3, 5)
x_coordinate = point[0] #3
y_coordinate = point[1] #5

Immutable Nature:
One of the main differences between tuples and lists is that tuples are
immutable, meaning their contents cannot be changed after creation:
point = (3, 5)
point[0] = 10 # This will result in an error

Tuple Packing and Unpacking:

Tuple packing is the process of creating a tuple with multiple values, and tuple
unpacking is the process of assigning the values of a tuple to multiple
variables:

coordinates = 4, 9 # Tuple packing


19
x, y = coordinates # Tuple unpacking

Advantages of Tuples:
 Immutable: Tuples are suitable for data that should not be changed
accidentally.
 Performance: Due to their immutability, tuples are slightly faster than lists in
certain operations.
 Hashable: Tuples can be used as keys in dictionaries, which require
immutability.

Use Cases:
Tuples are often used to represent items that should remain constant
throughout the program's execution, such as coordinates, RGB color values,
and database records.

2.73 Sets
A set is an unordered collection of unique elements in Python. Sets are useful
for storing and manipulating data when you want to ensure that each element
is unique and unordered.

Creating Sets:
Sets are created using curly braces {} or the built-in set() constructor:
fruits = {"apple", "banana", "orange"}
numbers = set([1, 2, 3, 4, 5])

Unique Elements:
Sets automatically eliminate duplicate values, ensuring that each element is
unique:
my_set = {1, 2, 2, 3, 3, 3} # Results in {1, 2, 3}

Set Operations:
Sets support various mathematical operations:
 union(): Returns a new set with all unique elements from both sets.
 intersection(): Returns a new set with elements common to both sets.
20
 difference(): Returns a new set with elements present in the first set but not
in the second.
 symmetric_difference(): Returns a new set with elements that are in either of
the sets, but not in both.

Modifying Sets:
Sets are mutable, allowing you to add and remove elements:
fruits = {"apple", "banana", "orange"}
fruits.add("grape") # Adds "grape" to the set
fruits.remove("banana") # Removes "banana" from the set

2.74 Dictionaries
Dictionaries are versatile data structures that allow you to store and manage
key-value pairs. Each value is associated with a unique key, enabling efficient
and fast retrieval of values based on their keys.

Creating Dictionaries:
Dictionaries are created using curly braces {} and specifying key-value pairs
separated by colons ::
person = {"name": "Alice", "age": 25, "city": "New York"}
scores = {"math": 95, "science": 89, "history": 75}

Accessing Dictionary Values:


Values in a dictionary are accessed using their corresponding keys:
person = {"name": "Alice", "age": 25, "city": "New York"}
name = person["name"] # "Alice"
age = person["age"] # 25

Modifying and Adding Entries:


Dictionaries are mutable, so you can modify values or add new key-value
pairs:
person = {"name": "Alice", "age": 25}
person["age"] = 30 # Updates the value for the "age"
key
21
person["city"] = "San Francisco" # Adds a new key-value pair

Dictionary Methods:
Dictionaries provide various methods for working with their keys and values:

 keys(): Returns a list of all keys.


 values(): Returns a list of all values.
 items(): Returns a list of key-value pairs as tuples.
 get(key): Returns the value associated with the key, or a default value if the
key doesn't exist.

2.8 Functions in Python


Functions are blocks of code that perform specific tasks and can be reused
throughout a program. They help organize code into modular and manageable
pieces, making code more readable, maintainable, and efficient.

Defining Functions:
Functions are defined using the def keyword, followed by the function name,
parameters in parentheses, and a colon. The function body is indented below:
def greet(name):
print("Hello, " + name)

Function Parameters:
Parameters are placeholders for values that you pass to the function when it's
called. Functions can have zero or more parameters:
def add(x, y):
return x + y

Function Calling:
To call a function, use its name followed by parentheses, and provide the
required arguments:
greet("Alice")
22
sum_result = add(3, 5)

Return Statements:
Functions can return values using the return statement. If no return statement is
used, the function returns None by default:
def square(x):
return x ** 2

Scope of Variables:
Variables defined inside a function are local to that function and have a limited
scope. They don't affect variables with the same names outside the function.

Default Parameters:
You can provide default values for function parameters. These default values
are used when the corresponding argument is not provided during function
call:
def greet(name="Guest"):
print("Hello, " + name)

Variable Number of Arguments:


Functions can accept a variable number of arguments using *args for
positional arguments and **kwargs for keyword arguments.

Lambda Functions:
Lambda functions (also known as anonymous functions) are concise, one-line
functions defined using the lambda keyword:
square = lambda x: x ** 2

Built-in Functions:
Python comes with a rich set of built-in functions that perform various
operations, such as len(), print(), max(), and min().

23
2.9 Object Oriented Programming in Python
Object-Oriented Programming (OOP) is a programming paradigm that focuses
on organizing code into objects, which are instances of classes. Classes define
the blueprint for creating objects with attributes (data) and methods
(functions).

Key Concepts of OOP:

Class: A class is a blueprint or template that defines the structure and behavior
of objects. It defines attributes (variables) and methods (functions) that objects
of that class will have.

Object: An object is an instance of a class. It represents a specific entity or


concept based on the class definition.

Attributes: Attributes are variables that hold data within an object. They
define the characteristics or properties of an object.

Methods: Methods are functions defined within a class that perform specific
actions or provide functionalities related to the class.

Encapsulation: Encapsulation refers to the bundling of data and methods that


operate on the data into a single unit (object). It helps in controlling access to
the data and ensures data integrity.

Inheritance: Inheritance is a mechanism where a new class (subclass or


derived class) can inherit attributes and methods from an existing class
(superclass or base class). It promotes code reuse and hierarchy.

Polymorphism: Polymorphism allows objects of different classes to be treated


as objects of a common superclass. It enables the same method name to behave
differently based on the context.

Abstraction: Abstraction involves simplifying complex reality by modeling


classes with essential attributes and methods while hiding unnecessary details.
24
Defining Classes:
Classes are defined using the class keyword, followed by the class name.
Attributes and methods are defined within the class block:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age

def bark(self):
print(f"{self.name} is barking")

Creating Objects:
Objects are created based on class definitions using the constructor (usually
the __init__ method):
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)

Inheritance:
Subclasses can inherit attributes and methods from a superclass:
class Labrador(Dog):
def __init__(self, name, age, color):
super().__init__(name, age)
self.color = color

Polymorphism:

Polymorphism allows different classes to implement the same method name


but with different behaviors:
def make_sound(animal):
animal.make_sound()

25
Chapter – 03
Introduction to Seaborn

Seaborn is a powerful and versatile data visualization library in Python, built on


top of Matplotlib. It provides a high-level interface for drawing attractive and
informative statistical graphics. Here’s an overview of Seaborn, organized with
subheadings:

1. Installation

26
To install Seaborn, you can use the following pip command:

Code -
pip install seaborn

2. Importing Seaborn

You can import Seaborn into your Python script or Jupyter Notebook as follows:

Code -
import seaborn as sns
import matplotlib.pyplot as plt

3. Key Features

 Built-in Themes and Color Palettes: Seaborn comes with several themes
and color palettes that improve the aesthetic appeal of your plots.
 Statistical Estimations: Seaborn can automatically perform statistical
estimations and plot the results, such as confidence intervals.
 Complex Plots Made Simple: Seaborn simplifies the creation of complex
visualizations, including heatmaps, violin plots, and pair plots.
 Data-Aware Plotting: Seaborn works seamlessly with Pandas DataFrames
and supports categorical data visualization.

4. Commonly Used Functions

4.1 Relational Plots

 scatterplot: Visualizes the relationship between two numeric variables.

Code -
sns.scatterplot(data=df, x='variable1', y='variable2')
plt.show()

 lineplot: Shows trends over time or ordered categories.

Code -
sns.lineplot(data=df, x='time', y='value')
plt.show()

4.2 Categorical Plots


27
 barplot: Displays an average value for each category.

Code -
sns.barplot(data=df, x='category', y='value')
plt.show()

 boxplot: Visualizes the distribution of data across categories.

Code -
sns.boxplot(data=df, x='category', y='value')
plt.show()

 violinplot: Combines the benefits of boxplots and KDE plots.

Code -
sns.violinplot(data=df, x='category', y='value')
plt.show()

4.3 Distribution Plots

 histplot: Plots the distribution of a single numerical variable.

Code -
sns.histplot(data=df['variable'])
plt.show()

 kdeplot: Plots the kernel density estimate of the distribution.

Code -
sns.kdeplot(data=df['variable'])
plt.show()

4.4 Matrix Plots

 heatmap: Visualizes data in a matrix form using color-coded cells.

Code -
sns.heatmap(data=corr_matrix, annot=True, cmap='coolwarm')
plt.show()

28
 clustermap: Plots a hierarchically clustered heatmap.

Code -
sns.clustermap(data=df.corr(), cmap='viridis')
plt.show()

4.5 Multi-Plot Grids

 pairplot: Creates a matrix of scatter plots for all pairs of numerical


variables.

Code -
sns.pairplot(df)
plt.show()

 FacetGrid: Allows creating multi-plot grids, useful for visualizing the


distribution of a variable across multiple categories.

Code -
g = sns.FacetGrid(df, col="category")
g.map(sns.histplot, "value")
plt.show()

5. Customizing Plots

Seaborn offers extensive customization options:

 Changing Aesthetics: Use sns.set_style() and sns.set_palette() to change


the style and color palette.

Code -
sns.set_style('whitegrid')
sns.set_palette('muted')

 Adding Titles and Labels: You can add titles, labels, and other annotations
using Matplotlib functions.

Code -
plt.title('Title of the Plot')
plt.xlabel('X-axis Label')

29
plt.ylabel('Y-axis Label')

 Figure Size and Aspect Ratio: Control the figure size using

Code –

plt.figure(figsize=(10, 6))

6. Integration with Pandas

Seaborn is designed to work seamlessly with Pandas DataFrames, allowing you to


directly pass DataFrame columns as arguments.

Code -
sns.barplot(data=df, x='column1', y='column2')

7. Saving Plots

You can save your Seaborn plots using Matplotlib’s savefig function.

Code -
plt.savefig('plot.png')

8. Examples and Use Cases

Seaborn is widely used in data science for exploratory data analysis (EDA), data
cleaning, and visualization of statistical relationships. It’s particularly useful for
visualizing distributions, relationships between variables, and understanding data
at a glance.

9. Conclusion

Seaborn is a powerful tool for creating visually appealing and informative


statistical graphics in Python. It simplifies complex visualizations and integrates
seamlessly with Pandas and Matplotlib. Whether you're performing exploratory
data analysis or creating publication-quality graphics, Seaborn is a valuable library
to include in your data science toolkit.

30
Chapter – 04
Introduction to Numpy

4.1 Introduction:
NumPy, short for Numerical Python, is a fundamental package for numerical
and scientific computing in Python. It provides support for arrays, matrices,
and a wide range of mathematical operations, making it an essential tool for
data manipulation, analysis, and computation in various scientific and
engineering domains.

4.2 Key Features:

31
Arrays: NumPy introduces the ndarray (n-dimensional array) data structure,
which is the core of its functionality. Arrays can be of various dimensions and
hold elements of the same data type.

Efficiency: NumPy's arrays are more memory-efficient and faster for


numerical operations compared to Python's built-in lists due to their contiguous
memory allocation and optimized C implementation.

Vectorized Operations: NumPy allows you to perform mathematical


operations on entire arrays without the need for explicit loops, a concept
known as vectorization. This greatly enhances computational efficiency.

Broadcasting: Broadcasting is a feature that enables element-wise operations


on arrays of different shapes, making array operations more flexible and
intuitive.

Array Indexing and Slicing: NumPy provides powerful ways to index and
slice arrays, allowing you to extract, modify, and manipulate subsets of data
efficiently.

Mathematical and Statistical Functions: NumPy includes a wide range of


mathematical functions for operations like trigonometry, logarithms,
exponentials, and statistical analysis.

Linear Algebra Operations: NumPy offers comprehensive linear algebra


functions, such as matrix multiplication, decomposition, solving linear
equations, and eigenvalue calculations.

Random Number Generation: NumPy's random module enables the


generation of random numbers for various distributions, which is useful for
simulations and statistical analysis.

4.3 Some Examples:


To use NumPy, you need to install it using the following command:
pip install numpy

Once installed, you can import NumPy in your Python code:


import numpy as np

32
Creating Arrays:
You can create arrays using various methods, such as np.array(), np.zeros(),
np.ones(), np.arange(), and more:

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
zeros_arr = np.zeros((2, 3))
ones_arr = np.ones((3, 3))

Array Operations:
NumPy supports element-wise operations, broadcasting, and mathematical
functions:

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
sum_result = a + b
product_result = a * b
square_root = np.sqrt(a)

Array Indexing and Slicing:


You can access and manipulate array elements using indexing and slicing:

arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])


subset = arr[2:7] # [2, 3, 4, 5, 6]

Linear Algebra:
NumPy offers extensive linear algebra capabilities:

A = np.array([[1, 2], [3, 4]])


B = np.array([[5, 6], [7, 8]])

matrix_product = np.dot(A, B)
eigenvalues, eigenvectors = np.linalg.eig(A)

Hence,

33
NumPy is a cornerstone of scientific computing in Python, providing essential
tools for handling numerical data, performing advanced mathematical
operations, and working with arrays and matrices. Its efficiency and rich set of
functionalities make it a valuable asset for data analysis, machine learning,
simulations, and a wide range of scientific endeavors. NumPy's seamless
integration with other libraries like SciPy, Matplotlib, and Pandas enhances its
utility in the broader Python ecosystem.

34

You might also like