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

Ad25201 Python For Data Science

The document contains important objective type questions and answers related to Python for Data Science, covering topics such as data types, functions, libraries, and basic programming concepts. It also includes short answer questions about Python's features, operators, and data structures. Additionally, it provides insights into data science project steps and tools used for data manipulation and visualization.

Uploaded by

Sj Je
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)
2 views67 pages

Ad25201 Python For Data Science

The document contains important objective type questions and answers related to Python for Data Science, covering topics such as data types, functions, libraries, and basic programming concepts. It also includes short answer questions about Python's features, operators, and data structures. Additionally, it provides insights into data science project steps and tools used for data manipulation and visualization.

Uploaded by

Sj Je
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

AD25201 PYTHON FOR DATA SCIENCE

Unit - I

Important Objective type questions

1. What is the correct file extension for Python files?

A .py B .PT C .Pyth D .Pyt

Answer: A

2. Which keywords are used to define a function in Python?


A ceremony B Funk C Define D Def

Answer: D

3. What is the output of `print(2**3)`?

A 9 B 23 C 6 D 8

Answer: D

4. What data type will `[1, 2, 3]` return?

A dict B list C set D tuple

Answer: B

5. Which of the following is an immutable data type in Python?

A tuple B set C list D dict

Answer: A

6. Which operator is used for exponentiation in Python?

A. ** B. * C. // D. Exp

Answer: A

7. What does `len("hello")` return?

A error B 5 C 7 D 6

Answer: B

8. What is the result of `5 // 2`?

A 2.0 B 3 C 2 D 2.5

Answer: C
9. Which keyword is used for conditional branching in Python?

A when B For C if D Select

Answer: C

10. What will `range(0, 3)` produce?

A 1, 2 B [ 0, 1, 2] C {1, 2, 3} D (0, 1, 2)

Answer: B

11. Which keyword is used to skip to the next iteration of a loop?

A Continue B skip C Next D pass

Answer: A

12. Which symbol is used to define a dictionary?

A {} B [] C <> D( )

Answer: A

13. What is the function in another function called?

A. inline B. nested [Link] D. Internal

Answer: B

14. What is a variable defined outside the function referred to as?

A. local variable B. Global variable C. Static variable D. None of above

Answer: B

[Link] is a ____________ language

A. low level language B. high level language C. Machine language D. Assembly language

Answer: B

16. What is the first step in a Data Science project?


a) Modeling
b) Data Cleaning
c) Problem Definition
d) Data Visualization
Answer: c) Problem Definition

17. What is data wrangling?


a) Data deletion
b) Data visualization
c) Data cleaning and transforming
d) Data encryption
Answer: c) Data cleaning and transforming
18. What is meant by ‘Big Data’?
a) Very large emails
b) Data that fits in Excel
c) Extremely large and complex datasets
d) Zoomed-in images
Answer: c) Extremely large and complex datasets

19. Which Python library is used for data manipulation?


a) NumPy
b) Matplotlib
c) Pandas
d) Seaborn
Answer: c) Pandas

20. What does [Link]() return in Pandas?


a) First 5 columns
b) Last 5 rows
c) First 5 rows
d) Column names
Answer: c) First 5 rows

21. Which library is used for numerical computation in Python?


a) Scikit-learn
b) NumPy
c) Pandas
d) Matplotlib
Answer: b) NumPy

22. What is the output of len([1,2,3]) in Python?


a) 3
b) 4
c) 2
d) Error
Answer: a) 3

23. Which command is used to install Python libraries?


a) [Link]()
b) [Link]()
c) pip install
d) setup install
Answer: c) pip install

24. What does standard deviation measure?


a) Central tendency
b) Spread of data
c) Mode
d) Mean
Answer: b) Spread of data
25. What is the mean of 2, 4, 6, 8, 10?
a) 5
b) 6
c) 8
d) 4
Answer: b) 6

26. Which library is commonly used for plots in Python?


a) NumPy
b) Seaborn
c) TensorFlow
d) NLTK
Answer: b) Seaborn

27. What does a box plot show?


a) Relationships
b) Mean only
c) Data distribution & outliers
d) Text classification
Answer: c) Data distribution & outliers

28. A heatmap is useful for?


a) Checking correlation
b) Calculating averages
c) Encoding text
d) Scaling features
Answer: a) Checking correlation

29. Which chart is best for time series data?


a) Pie chart
b) Bar chart
c) Line chart
d) Histogram
Answer: c) Line chart

30. What type of chart is ideal for showing proportions?


a) Bar chart
b) Pie chart
c) Histogram
d) Boxplot
Answer: b) Pie chart

31. What is the file extension for a Python file?


a) .text
b) .docx
c) .py
d) .csv
Answer: c) .py
32. CSV stands for?
a) Column-Separated Value
b) Character-Set Value
c) Comma-Separated Values
d) Code Storage Version
Answer: c) Comma-Separated Values

33. What does API stand for?


a) Application Programming Interface
b) Automated Programming Integration
c) Applied Python Interface
d) Algorithm Processing Info
Answer: a) Application Programming Interface

34. What does EDA stand for?


a) Enhanced Data Approach
b) Exploratory Data Analysis
c) Excel Data Algorithm
d) Estimated Data Accuracy
Answer: b) Exploratory Data Analysis

35. What is the purpose of a histogram?


a) Count frequency
b) Show average
c) Plot regression
d) Encode labels
Answer: a) Count frequency

36. Time series data depends on?


a) Randomness
b) Seasonality & trend
c) Static value
d) Classification
Answer: b) Seasonality & trend

37. What does .describe() show in Pandas?


a) Dataset structure
b) Summary statistics
c) Column names
d) Histogram
Answer: b) Summary statistics

38. How do you remove an element from a list in Python?

[Link](element) [Link](index) [Link](element) [Link](element)


Answer: B
39. Which method is used to add elements from one list to another in Python?

[Link]() B merge() C. extend() D. append()


Answer: C

40. What will be the output of the following code snippet?


numbers = [1, 2, 3, 4, 5]
numbers[1] = 9
print(numbers)

A. [1, 9, 3, 4, 5] B.[1, 2, 3, 4, 5] C.[9, 2, 3, 4, 5] [Link]

Answer: A

41. What will be the output of the following code snippet?

numbers = [1, 2, 3, 4, 5]
sliced_numbers = numbers[1:4]
print(sliced_numbers)

A. [1, 2, 3, 4, 5] B.[2, 3, 4] C. [1, 2, 3] D. [3, 4, 5]


Answer: B

42. What will be the output of the following code snippet?

fruits = ['apple', 'banana', 'cherry']


[Link]('banana')
print(fruits)
A. ['apple', 'banana', 'cherry'] B. ['apple', 'cherry'] C.['banana', 'cherry'] D. Error

Answer: B

43. In Python, which module is commonly used for array operations?

[Link] [Link] C. numpy [Link]


Answer: C

44. How do you perform element-wise addition of two NumPy arrays, arr1 and arr2?

[Link](arr2) [Link](arr1, arr2) C.arr1 + arr2 D. [Link](arr1, arr2)


Answer: C

45. What does the NumPy function [Link]((arr1, arr2), axis=0) do?

[Link] the arrays along the specified axis.


[Link] the arrays element-wise.
[Link] the arrays element-wise.
D. Computes the cross product of the arrays.

Answer: A
46. What is the output of the code [Link](2, 10, 2)?

A.[2, 4, 6, 8] B.[2, 4, 8] C.[2, 6] D.[2, 4, 8, 10]


Answer: A

47. Given a NumPy array arr = [Link]([[1, 2, 3], [4, 5, 6]]), what does [Link]
return?

A. (2, 3) B.(3, 2) C.(2,) D.(3,)


Answer: A

48. How can you create a NumPy array filled with zeros of shape (4, 4)?

A. [Link]((4, 4)) [Link]((4, 4)) C. [Link]((4, 4)) D. [Link]((4, 4), 0)


Answer: A

49. Which method is used to remove rows or columns with missing values?
A. fillna()
B. dropna()
C. remove_null()
D. clean()

Answer: B

50. Which function allows you to pivot a DataFrame into a longer format?
A. pivot_table()
B. melt()
C. stack()
D. unstack()

Answer: B

Note: In addition to this, refer Multiple choice question answers in the back of each unit.

Important 3 Marks Question Answer

1. What is Python?
Python is a dynamic, high-level, free open source, and interpreted programming language. It
supports object-oriented programming as well as procedural-oriented programming.

2. Define Python Interpreter.

A Python Interpreter is the program that reads and executes Python code. It translates the Python
instructions into machine-readable form line by line, so the computer can understand and run
them. When we run a Python program, code passes through Python Interpreter, which is
responsible for:
 Checking your code for errors.

 Converting it into an intermediate form called bytecode.

 Sending it to the Python Virtual Machine (PVM) for execution.

3. List any two features of python.

1. Free and Open Source

Python language is freely available at the official website and you can download it from the
given download link below click on the Download Python keyword. Download Python Since it
is open-source, this means that source code is also available to the public. So you can download
it, use it as well as share it.

2. Easy to code

Python is a high-level programming language. Python is very easy to learn the language as
compared to other languages like C, C#, Javascript, Java, etc. It is very easy to code in the
Python language and anybody can learn Python basics in a few hours or days. It is also a
developer-friendly language.

4. What are arithmetic operators in python.


Python provides seven main arithmetic operators to perform common mathematical
calculations on numeric values like integers and floats.

Standard Arithmetic Operators

 Addition (+): Adds two values together (e.g., 10 + 5 results in 15).


 Subtraction (-): Subtracts the right operand from the left (e.g., 10 - 5 results in 5).
 Multiplication (*): Multiplies two values (e.g., 2 * 3 results in 6).
 Division (/): Divides the left operand by the right. In Python 3, this always returns a
float, even if the numbers divide evenly (e.g., 10 / 2 results in 5.0).
 Modulus (%): Returns the remainder of the division (e.g., 10 % 3 results in 1).
 Exponentiation (**): Raises the first operand to the power of the second (e.g., 2 ** 3
results in 8).
 Floor Division (//): Divides two numbers and rounds the result down to the nearest
whole number, discarding any decimal part (e.g., 11 // 3 results in 3).

5. What is the purpose of If statement in python?

The if statement contains a logical expression using which data is compared and a
decision is made based on the result of the comparison.

Syntax:

if expression:

statement(s)
If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if
statement is executed. If boolean expression evaluates to FALSE, then the first set of
code after the end of the if statement(s) is executed.

6. What is the difference between break and continue?


The break statement terminates the loop containing it and control of the program flows
to the statement immediately after the body of the loop. If break statement is inside a
nested loop (loop inside another loop), break will terminate the innermost loop.
The continue statement is used to skip the rest of the code inside a loop for the
current iteration only. Loop does not terminate but continues on with the next iteration.

7. What are variables in Python?


Variables are nothing but reserved memory locations to store values. This means that
when you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides
what can be stored in the reserved memory. Therefore, by assigning different data types
to variables, you can store integers, decimals or characters in these variables.

8. Define data types in python. List any 4 built in data types.


Python's built-in data types are categorized into several groups based on their characteristics
and the operations they support. Everything in Python is an object, meaning each data type is a
class and variables are instances of these classes.

Numeric Types: Used to represent numbers.

 int: Holds whole numbers of unlimited length (e.g., 10, -5).


 float: Represents real numbers with decimal points, accurate up to 15 decimal places
(e.g., 10.5).
 complex: Consists of a real and an imaginary part, written as a + bj.

Text Type: Used for textual data.

 str: A sequence of Unicode characters enclosed in quotes.

Sequence Types: Used to store ordered collections of items.

 list: A mutable, ordered collection that can hold different data types (e.g., [1,
"apple", 3.5]).
 tuple: An immutable, ordered collection (e.g., (1, 2, 3)).
 range: Represents a sequence of numbers, commonly used for looping.

9. What does the len() function do?


The len() function in Python is used to get the number of items in an object. It is most
commonly used with strings, lists, tuples, dictionaries and other iterable or container types. It
returns an integer value representing the length or the number of elements.
Example:

s = "csiit"
l = len(s)
print(l)

Output: 5

10. How are variables declared in python?

Variables are containers for storing data values.


Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
x=5
y = "John"
print(x)
print(y)

Output:

5
John

11. What is a list in python?

List is a collection which is ordered and changeable and allows duplicate members.
(Grow and shrink as needed, sequence type, sortable). To use a list, you must declare it
first. Do this using square brackets and separate values with commas. We can construct /
create list in many ways. Ex:

>>> list1=[1,2,3,'A','B',7,8,[10,11]]

>>> print(list1)

[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]

12. Differentiate list and tuple.

lists and tuples both store collections of data, but differ in mutability, performance and memory
usage. Lists are mutable, allowing modifications, while tuples are immutable.

[Link] List Tuple


Tuples are immutable(cannot be
1 Lists are mutable(can be modified).
modified).
2 Iteration over lists is time-consuming. Iterations over tuple is faster
Lists are better for performing operations, such Tuples are more suitable for accessing
3
as insertion and deletion. elements efficiently.
4 Lists consume more memory. Tuples consumes less memory

5 Lists have several built-in methods. Tuples have fewer built-in methods.
13. What is a dictionary?

Python dictionary is a data structure that stores information in key-value pairs. While keys must
be unique and immutable (like strings or numbers), values can be of any data type, whether
mutable or immutable. This makes dictionaries ideal for accessing data by a specific name rather
than a numeric position like in list.

data = { "name": "Jake", "age": 22 }


print(data)

Output:

{'name': 'Jake', 'age': 22}

14. What is a set in python?

Set is an unordered collection of unique elements. Unlike lists or tuples, sets do not allow
duplicate values i.e. each element in a set must be unique. Sets are mutable, meaning you can
add or remove items after a set has been created.
Sets are defined using curly braces {} or the built-in set() function. They are particularly
useful for membership testing, removing duplicates from a sequence, and performing
common mathematical set operations like union, intersection, and difference.
A set refers to a collection of distinct objects. It is used to group objects together and to
study their properties and relationships. The objects in a set are called elements or members
of the set.

12 Marks Questions

1. Describe the role of the python interpreter in program execution with an example.

A Python Interpreter is the program that reads and executes Python code. It translates the Python
instructions into machine-readable form line by line, so the computer can understand and run
them. When we run a Python program, code passes through Python Interpreter, which is
responsible for:

 Checking your code for errors.

 Converting it into an intermediate form called bytecode.

 Sending it to the Python Virtual Machine (PVM) for execution.

Working of Interpreter

The step-by-step process of how the Python code runs:

1. Python Source Code (.py file): You write your program in a .py file.

2. Parser and AST (Syntax Check -> Abstract Syntax Tree): Python checks the code for syntax
errors and converts it into an AST (Abstract Syntax Tree), which represents the program
structure.
3. Bytecode (.pyc file in __pycache__): The AST is compiled into bytecode, a low-level instruction
set. This bytecode may also be saved in the __pycache__ folder for reuse.

4. Python Virtual Machine (Executes Bytecode): The PVM executes the bytecode line by line and
translates it into machine instructions.

5. Output (Result on Screen): Finally, the program’s result is shown on the screen (for example, via
print()).

To visualize this at a high level, here’s a simple diagram of how an interpreter processes your
code:

Working of Interpreter

Example

This program takes two inputs as a and b and prints sum in the third variable which is c. It
follows sequential as well as functional execution of programs

a=3
b=7
c=a+b
print(c)

Output:
10

2. Discuss python data types in details with example for each type.

Data types:

The data stored in memory can be of many types. For example, a student
roll number is stored as a numeric value and his or her address is stored as
alphanumeric characters. Python has various standard data types that are
used to define the operations possible on them and the storage method for
each of them.
Integer
Int, or integer, is a whole number, positive or negative, without
decimals, of unlimited length.

>>> print(24656354687654+2)
24656354687656
>>> print(20)
20

>>> type(10)
<class 'int'>
>>> a=11
>>> print(type(a))
<class 'int'>

Float:

Float, or "floating point number" is a number, positive or negative,


containing one or more decimals. Float can also be scientific numbers with an
"e" to indicate the power of 10.

>>> y=2.8
>>> y
2.8

Boolean:

Objects of Boolean type may have one of two values, True or False:

>>> type(True)

<class 'bool'>

String:

1. Strings in Python are identified as a contiguous set of characters


represented in the quotation marks. Python allows for either pairs of single or
double quotes.

• 'hello' is the same as "hello".


• Strings can be output to screen using the print function. For example:
print("hello").

>>> print("mrcet college")

mrcet college

>>> type("mrcet college")

<class 'str'>

3. Write notes on the following basic functions


print(), input(),len(), type() and range()

Input()

Python's input() function is used to take user input. By default, it returns the user input in form of
a string.

name = input("Enter your name: ")


print("Hello,", name, "! Welcome!")

Output

Enter your name: csiit

Hello, csiit Welcome!

The code prompts the user to input their name, stores it in the variable "name" and then prints a
message addressing the user by their entered name.

Print()

The print() function allows us to display text, variables and expressions on the console. In the
below example, "Hello, World!" is a string literal enclosed within double quotes. When executed,
this statement will output the text to the console.

print("Hello, World!")

Output
Hello, World!

Len()

The len() function returns the number of items in an object.

When the object is a string, the len() function returns the number of characters in the string.
mylist = ["apple", "banana", "cherry"]
x = len(mylist)

Output: 3

Range( )

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1
(by default), and stops before a specified number.

x = range(6)
for n in x:
print(n)

Output:

0
1
2
3
4
5

4. Explain in detail the different types of operators in python with examples.

Python operators are special symbols and keywords used to perform computations on variables
and values. They are categorized into several functional groups:
1. Arithmetic Operators

It is used for standard mathematical calculations:

 Addition (+): Adds two values (e.g., 5 + 2 = 7).


 Subtraction (-): Subtracts right from left (e.g., 5 - 2 = 3).
 Multiplication (*): Multiplies values (e.g., 5 * 2 = 10).
 Division (/): Divides and returns a float (e.g., 5 / 2 = 2.5).
 Floor Division (//): Divides and returns the largest integer less than or equal to the result
(e.g., 5 // 2 = 2).
 Modulus (%): Returns the remainder of division (e.g., 5 % 2 = 1).
 Exponentiation ():** Raises to power (e.g., 5 ** 2 = 25).

2. Comparison (Relational) Operators


It is used to compare two values and return a Boolean (True or False):

 Equal (==): x == y.
 Not Equal (!=): x != y.
 Greater than (>), Less than (<): Standard numeric or lexicographic comparisons.
 Greater than or equal to (>=), Less than or equal to (<=): Inclusive comparisons.

3. Logical Operators
It is Used to combine conditional statements:

 and: Returns True if both statements are true.


 or: Returns True if at least one statement is true.
 not: Reverses the Boolean result (e.g., not True is False).

4. Assignment Operators
It is used to assign values to variables, often combined with arithmetic for shorthand:

 Simple (=): x = 5.
 Compound: Performs operation then assigns result (e.g., +=, -=, *=, /=, //=, %=, **=).
 Walrus (:=): Assigns a value to a variable within an expression.

5. Bitwise Operators
It is used to operate on the binary representations of integers:

 AND (&), OR (|), XOR (^), NOT (~): Standard bit-level logic.
 Shift (<<, >>): Shifts bits left or right.

6. Special Operators

 Identity (is, is not): Checks if two variables refer to the exact same object in memory.
 Membership (in, not in): Tests if a value is present in a sequence like a list, string, or
dictionary.

5. Write a python program to display all even numbers between 1 and 100 using a loops.

for num in range(1, 101):


if num % 2 == 0:
if num <= 50:
print(num, end=" ")
else:
if num == 52:
print()
print(num, end=" ")

6. Describe flow control statements in python with example for if, elif, else and looping constructs.

Conditional Statements

Conditional statements in Python allow us to check for certain conditions and perform actions
based on the outcome of those checks. There are several types of conditional statements in
Python, including:

 if statement
 if else statement
 if elif else statement
 nested if else statement

Let’s take a look at each of these in more detail.

1. if statement

The if statement is used to check if a certain condition is true, and if so, execute a specific block
of code. Here’s an example:
age = 18

if age >= 18:


print("You are old enough to vote.")

In this example, the if statement checks if the value of the variable age is greater than or equal to
18. If it is, the code inside the if statement is executed, which in this case is simply printing a
message to the console.

2. if else statement

The if else statement is used to execute one block of code if a condition is true, and another block
of code if the condition is false. Here’s an example:

age = 16

if age >= 18:


print("You are old enough to vote.")
else:
print("You are not old enough to vote yet.")

In this example, the if statement checks if the value of age is greater than or equal to 18. If it is,
the message "You are old enough to vote." is printed. If it is not, the message "You are not old
enough to vote yet." is printed instead.

3. if elif else statement

The if elif else statement is used to check multiple conditions, and execute a specific block of
code based on which condition is true. Here’s an example:

age = 16

if age >= 18:


print("You are old enough to vote.")
elif age >= 16:
print("You can drive but cannot vote.")
else:
print("You cannot drive or vote yet.")

In this example, the first if statement checks if the value of age is greater than or equal to 18. If it
is, the message "You are old enough to vote." is printed. If not, the elif statement checks if age is
greater than or equal to 16. If it is, the message "You can drive but cannot vote." is printed. If
neither of these conditions are true, the else statement executes, and the message "You cannot
drive or vote yet." is printed.

4. nested if else statement

The nested if else statement is used when we need to check a condition inside another condition.
Here’s an example:

age = 18
gender = "female"

if age >= 18:


if gender == "male":
print("You are a male and old enough to vote.")
else:
print("You are a female and old enough to vote.")
else:
print("You are not old enough to vote yet.")

In this example, the first if statement checks if age is greater than or equal to 18. If it is, the
nested if statement checks if the value of gender is "male". If it is, the message "You are a male
and old enough to vote." is printed. If not, the message "You are a female and old enough.

Loops in Python

A loop is a repetitive statement or task.

While Loop Statement:

A while loop statement in Python is used to repeatedly execute a block of code as long as a
condition is true. It is typically used when you don’t know how many times the loop will run in
advance.

# Print numbers from 1 to 5 using a while loop


count = 1
while count <= 5:
print(count)
count += 1

For Loop Statement:

A for-loop statement in Python is used to iterate over a sequence (such as a list, tuple, or string)
and perform a certain action for each item in the sequence.

# Print each character in a string using a for loop


word = "Python"
for letter in word:
print(letter)

UNIT – II

Important 3 Marks Question Answer

1. Define a function in python.


Python Functions are a block of statements that does a specific task. The idea is to put some
commonly or repeatedly done task together and make a function so that instead of writing the
same code again and again for different inputs, we can do the function calls to reuse code
contained in it over and over again.

2. What are function arguments?

Arguments are the values passed inside the parenthesis of the function. A function can have
any number of arguments separated by a comma.

Syntax

def function_name(parameters):
# body of the function
return expression

3. What is return statement?

The return statement ends a function and sends a value back to the caller. It can return any
data type, multiple values, or None if no value is given.

Syntax:

return [expression]

Parameters: return ends the function, [expression] is the optional value to return

4. What is a class in python?

A class is a user-defined template for creating objects. It bundles data and functions
together, making it easier to manage and use them. When we create a new class, we
define a new type of object. We can then create multiple instances of this object type.

Creating Class

Classes are created using class keyword. Attributes are variables defined inside class and
represent properties of the class. Attributes can be accessed using dot . operator (e.g.,
MyClass.my_attribute).
# define a class
class Dog:
sound = "bark" # class attribute

5. Define object.

An object is a specific instance of a class. It holds its own set of data (instance variables)
and can invoke methods defined by its class. Multiple objects can be created from same
class, each with its own unique attributes.
class Dog:
sound = "bark"

dog1 = Dog() # Creating object from class


print([Link]) # Accessing the class

Output
Bark

6. What is the difference between ‘w’ and ‘a’ mode?


"w" mode "a" mode

The "w" mode in file opening is used for The "a" mode in file opening is used for appending data to
writing data to a file. a file.

If the file exists, Python will truncate If the file exists, the data in the file is retained and new
existing data and over-write in the file. data being written will be appended to the end of the file.

7. What is the purpose of [Link]()?

[Link]() returns the square root of a number. It is an inbuilt function in


the Python programming language, provided by the math module.
Example:

import math

# square root of 4
print([Link](4))

Output

2.0

8. What is file handling?




File handling refers to the process of performing operations on a file, such as creating,
opening, reading, writing and closing it through a programming interface. It involves
managing the data flow between the program and the file system on the storage device,
ensuring that data is handled safely and efficiently.

Opening a File
To open a file, we can use open() function, which requires file-path and mode as
arguments.

Syntax:
file = open('[Link]', 'mode')
 [Link]: name (or path) of the file to be opened.
 mode: mode in which you want to open the file (read, write, append, etc.).
Note: If you don’t specify the mode, Python uses 'r' (read mode) by default.
Basic Example: Opening a File

f = open("[Link]", "r")
print(f)

Closing a File
[Link]() method closes the file and releases the system resources. If the file was
opened in write or append mode, closing ensures that all changes are properly saved.

file = open("[Link]", "r")


# Perform file operations
[Link]()
We will also see later how closing can be handled automatically using the with statement
and how to ensure files close properly using exception handling.

Checking File Properties

Once the file is open, we can check some of its properties:

f = open("[Link]", "r")
print("Filename:", [Link])
print("Mode:", [Link])
print("Is Closed?", [Link])

[Link]()
print("Is Closed?", [Link])

Output
Filename: [Link]
Mode: r
Is Closed? False
Is Closed? True

Reading a File
Reading a file can be achieved by [Link]() which reads the entire content of the file.
After reading, it’s good practice to close the file to free up system resources.
Example: Reading a File in Read Mode (r)

file = open("[Link]", "r")


content = [Link]()
print(content)
[Link]()
Output
Hello world
GeeksforGeeks
123 456
Writing a File
Writing to a file is done using the mode "w". This creates a new file if it doesn’t exist, or
overwrites the existing file if it does. The write() method is used to add content. After
writing, make sure to close the file.
Example: Writing to a file (overwrites if file exists)

with open("[Link]", "w") as file:


[Link]("Hello, Python!\n")
[Link]("File handling is easy with Python.")

print("File written successfully")

Output
Hello, Python!
File handling is easy with Python.

Using with Statement

Instead of manually opening and closing the file, you can use the with statement, which
automatically handles closing.
with open("[Link]", "r") as file:
content = [Link]()
print(content)
Output
Hello, World!

9. What is exception handling?


Python Exception Handling allows a program to gracefully handle unexpected
events (like invalid input or missing files) without crashing. Instead of terminating
abruptly, Python detect the problem, respond to it, and continue execution when
possible.

n = 10
try:
res = n / 0
except ZeroDivisionError:
print("Can't be divided by zero!")

Output

Can't be divided by zero!


Dividing a number by 0 raises a ZeroDivisionError. The try block contains code that may fail
and except block catches the error, printing a safe message instead of stopping the
program.
10. What is import statement?

The import statement in Python is the tool used to bring code from one module (a file containing
Python code) into another. This allows to reuse functions, classes, and variables without rewriting
them. The most common way to import is using the import keyword followed by the module name.
Access its contents using dot notation.

import math

# Access the pi constant using dot notation


print([Link]) # Output: 3.141592653589793

11. Define string methods.

Python string methods is a collection of in-built Python functions that operates on strings.

Python string is a sequence of Unicode characters that is enclosed in quotation marks.

lower(): Converts all uppercase characters in a string into lowercase


upper(): Converts all lowercase characters in a string into uppercase
title(): Convert string to title case
swapcase(): Swap the cases of all characters in a string
capitalize(): Convert the first character of a string to uppercase

# Python3 program to show the


# working of upper() function
text = 'geeKs For geEkS'

# upper() function to convert


# string to upper case
print("\nConverted String:")
print([Link]())

# lower() function to convert


# string to lower case
print("\nConverted String:")
print([Link]())

# converts the first character to


# upper case and rest to lower case
print("\nConverted String:")
print([Link]())

# swaps the case of all characters in the string


# upper case character to lowercase and viceversa
print("\nConverted String:")
print([Link]())

# convert the first character of a string to uppercase


print("\nConverted String:")
print([Link]())

# original string never changes


print("\nOriginal String")
print(text)

Output

Converted String:
GEEKS FOR GEEKS

Converted String:
geeks for geeks

Converted String:
Geeks For Geeks

Converted String:
GEEkS fOR GEeKs

Original String
geeKs For geEkS

12 Marks Questions

1. Explain user-defined functions in python with suitable examples.

There are two types of functions in python, they are: the


built-in/predefined functions and the user-defined functions.

Built-in Functions: These type of functions are predefined in python;


all we need to do is simply to simply declare them and python takes
care of the rest. Examples are: print(), input(), int(), max(), min() and
so on.

User-Defined Functions: These type of functions are defined by the


user using the “def” keyword; user-defined functions only run when
they are called. Data can also be passed into the functions in the form
of parameters and arguments.
Syntax:

def name_of_function(parameter1,parameter2)#Parameters are optional

Below is an example of a user-defined function:

# a user-defined function
def my_function():
print('Welcome!')
#Function creation
def my_function():
print('Welcome!')

#Function call
my_function()

The output:

>>> %Run -c $EDITOR_CONTENT


Welcome!

This explains the phrase ‘user-defined functions only run when they
are called’ in its definition above. Calling a function is simply telling
python to execute the command in the “def code block”.

Parameters and arguments in user-defined functions

A parameter allows the code in the function to access the arguments


for a particular function’s invocation. We can also have multiple
parameters in a python function.

Return Values

The “return” function can be used to return and print the result
computation that is carried out when a function is called instead of the
“print” statement.

For example:
def calculateAverage(param1, param2, param3):
# Add up the numbers and divide by the count of numbers
total = param1 + param2
average = total / 2.0
return average # returns the answer to the caller

# Passing arguments to the function


average1 = calculateAverage(200, 350, 103)
average2 = calculateAverage(-30, 552, 12.50)
average3 = calculateAverage(10.4, 25, -100)
print('The three averages are:', average1, average2, 'and', average3)
>>> %Run -c $EDITOR_CONTENT
The three averages are: 275.0 261.0 and 17.7

2. Explain how lists can be passed to functions. Write an example program.

Passing list by Reference

When we pass a list to a function by reference, it refers to the original list. If we make any
modifications to the list, the changes will reflect in the original list.

Example:

def fun(l):
for i in l:
print(i,end=" ") # Iterates
l = [1, 2, 3, 4]
fun(l)

Output

1 2 3 4

Explanation:

 This function prints each element of the list l.

 list l is passed, printing the numbers one by one.

By using *args (Variable-Length Arguments)

This allows us to pass a list to a function and unpack it into separate arguments. It is useful when
we don't know the exact number of arguments the function will receive.

Example:

def fun(*args):
for i in args:
print(i,end=" ")
l = [1, 2, 3, 4, 5]
fun(*l)
Output

1 2 3 4 5

Explanation:

 This function unpacks the list l into separate arguments.

 It prints each element on the same line, separated by spaces.

Passing a copy

Shallow copy of a list creates a new list with the same elements, ensuring the original list
remains unchanged. This is useful when we want to work with a duplicate without modifying the
original.

Example:

def fun(l):
[Link](6)
a = [1, 2, 3, 4, 5]
b = [Link]() # shallow copy of list
fun(b)
print(a) # Original list
print(b) # Modified copy

Output

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

Explanation:

 Shallow copy of l is created, keeping the original list unchanged.

 Copied list is modified by appending 6, while the original list remains the same.

3. Describe recursion in python with an example program.

Recursion is a programming technique where a function calls itself either directly or indirectly to
solve a problem by breaking it into smaller, simpler subproblems. A recursive function is just like
any other function except that it calls itself in its body. Let's see basic structure of recursive function:

def recursive_function(parameters):
if base_case_condition:
return base_result
else:
return recursive_function(modified_parameters)
Recursive function contains two key parts:
 Base Case: The stopping condition that prevents infinite recursion.
 Recursive Case: The part of the function where it calls itself with modified parameters.
Example 1: This code defines a recursive function to calculate factorial of a number, where function
repeatedly calls itself with smaller values until it reaches the base case.

def factorial(n):
if n == 0: # Base case
return 1
else: # Recursive case
return n * factorial(n - 1)

print(factorial(5))

Output
120
Explanation:
 Base Case: When n == 0, recursion stops and returns 1.
 Recursive Case: Multiplies n with the factorial of n-1 until it reaches the base case.

4. Explain try, except , else and finally blocks with suitable example

An Exception is an Unexpected Event, which occurs during the execution of the program. It
is also known as a run time error. When that error occurs, Python generates an exception
during the execution and that can be handled, which prevents your program from
interrupting.

In this code, The system can not divide the number with zero so an exception is raised.
a = 5
b = 0
print(a/b)

Output
Traceback (most recent call last):
File "/home/[Link]", line 3, in
<module>
print(a/b)
ZeroDivisionError: division by zero

Exception handling with try, except, else, and finally

 Try: This block will test the excepted error to occur


 Except: Here you can handle the error
 Else: If there is no exception then this block will be executed
 Finally: Finally block always gets executed either exception is generated or not
 First try clause is executed i.e. the code between try and except clause.
 If there is no exception, then only try clause will run, except clause will not get executed.
 If any exception occurs, the try clause will be skipped and except clause will run.
 If any exception occurs, but the except clause within the code doesn’t handle it, it is
passed on to the outer try statements. If the exception is left unhandled, then the
execution stops.
 A try statement can have more than one except clause.

Let us try to take user integer input and throw the exception in except block.

# Python code to illustrate working of try()


def divide(x, y):
try:
# Floor Division : Gives only Fractional
# Part as Answer
result = x // y
print("Yeah ! Your answer is :", result)
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")

# Look at parameters and note the working of Program


divide(3, 2)
divide(3, 0)

Output:
Yeah ! Your answer is : 1
Sorry ! You are dividing by zero

5. Differentiate between text files and binary files. Write a program to copy contents from one file
to another.

Text File Binary File

A text file consists of human readable A binary file is made up of non-human readable
characters, which can be opened by any text characters and symbols, which require specific
editor. programs to access its contents.

A text file is a file that stores information in


A binary file is a file that stores the information in the
the form of a stream of ASCII or Unicode
form of a stream of bytes.
characters.

In text files, each line of text is terminated


In a binary file, there is no delimiter for a line and no
with a special character known as EOL (End
character translations occur here.
of Line) character.

Files with extensions like .txt, .py, .csv etc Files with extensions like .jpg, .pdf etc are some
are some examples of text files. examples of binary files.
6. Write a python program to create a class ‘student’ with data members name, roll number and
marks. Include methods to display details.

class Student:
# Constructor to initialize data members
def __init__(self, name, roll_number, marks):
[Link] = name
self.roll_number = roll_number
[Link] = marks # Method to display student details
def display_details(self):
print("\n--- Student Information ---")
print(f"Name: {[Link]}")
print(f"Roll Number: {self.roll_number}") print(f"Marks: {[Link]}")
# Creating an instance (object) of the Student class
student1 = Student("Alex Smith", "A101", 85)
# Calling the method to display details
student1.display_details()

 __init__ method: This is the standard constructor in Python used to assign values to the object's
properties when it is first created.

 self parameter: This is a reference to the current instance of the class and is used to access variables
that belong to the class.

 Data Members: name, roll_number, and marks are stored as instance variables.

 Methods: The display_details function is defined within the class to print the stored data in a
readable format.

7. Write a program to count vowels , consonants, digits and write data into a text file.
def vowel():
f=open(“[Link]”,”r”)
vowels=”aeiouAEIOU”
count=0
for line in f:
for char in line:
if char in vowels:
count=count+1
print(“the number of vowels in the file is”,count)
[Link]()

vowel()

UNIT – III

Important 3 Marks Question Answer

1. What is Numpy array?

NumPy is a homogeneous data structure (all elements are of the same type). It is significantly
faster than Python's built-in lists because it uses optimized C language style storage where
actual values are stored at contiguous locations (not object reference). It also supports
vectorized computations. It supports vectorized operations (no need for loops).

Create NumPy Arrays


To start using NumPy, import it as follows:
import numpy as np

NumPy array’s objects allow us to work with arrays in Python. The array object is called ndarray.
NumPy arrays are created using the array() function.

import numpy as np
# Creating a 1D array
x = [Link]([1, 2, 3])
# Creating a 2D array
y = [Link]([[1, 2], [3, 4]])
# Creating a 3D array
z = [Link]([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(x)
print(y)
print(z)

Output

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

2. How can arrays be joined in Numpy?

Joining NumPy arrays means combining multiple arrays into one larger array. For
example, joining two arrays [1, 2] and [3, 4] results in a combined array [1, 2, 3, 4].
Let’s explore some common ways to join arrays using NumPy.

1. Using [Link]()
[Link]() joins two or more arrays along an existing axis without adding new
dimensions. It is fast and efficient for straightforward array joining.

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

Output

[1 2 3 4]
This code combines them into one longer list [1, 2, 3, 4] using NumPy’s concatenate
function which just sticks the arrays together end to end.

2. Using [Link]() / [Link]() / [Link]()


[Link](), [Link]() and [Link]() are convenient wrappers around
concatenate for stacking arrays horizontally, vertically or depth-wise making code more
readable and expressive.

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

res_h= [Link]((a, b))


print("[Link]: ", res_h)

res_v= [Link]((a, b))


print("[Link]: ", res_v)

res_d= [Link]((a,b))
print("[Link]: ", res_d)

Output

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

3. How can arrays be split in Numpy?

Splitting arrays means dividing a single NumPy array into multiple smaller sub-arrays.
NumPy provides several functions that make this easy by allowing you to split arrays along
different directions (rows, columns, depth).
Below are some important terms to understand when splitting arrays:
 Axis: The direction along which the array is split (0 for rows, 1 for columns).
 Sub-arrays: Smaller arrays created after splitting the original array.
 Splitting Methods: Functions like [Link](), [Link](), [Link]() and np.array_split().
 Equal vs. Unequal Splits: Splits can divide data evenly, or slightly unevenly if needed
(using array_split()).
Example: This example splits a 1D array into three smaller parts using np.array_split().

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

[array([1, 2]), array([3, 4]), array([5, 6])]


Explanation: np.array_split(arr, 3) divides the array into 3 sub-arrays, splitting elements as
evenly as possible.

Splitting Methods
NumPy provides several built-in functions to split arrays into smaller parts. These methods
help divide 1D, 2D, and even 3D arrays along different axes. Let's go through each method
one by one with simple examples, outputs, and clear explanations.

1. [Link]()

[Link]() is used to divide an array into equal-sized subarrays. The number of splits
must perfectly divide the size of the array along the chosen axis. If equal division is not
possible, NumPy will raise an error.

import numpy as np
arr = [Link](6)
res = [Link](arr, 2)
print(res)

Output

[array([0, 1, 2]), array([3, 4, 5])]

4. Define array slicing.

Slicing is a method for taking out an array section frequently used for subsetting and
modifying data inside arrays. In Python, Slicing gains considerably more strength when
used with multi-dimensional arrays because it may be applied along several axes.

1-D Array Slicing

In a 1-D NumPy array, slicing is performed using the [start:stop: step] notation.
import numpy as np

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


# Slice from index 1 to 3
sliced_arr = arr[1:4]
print(sliced_arr)
Output:
[1 2 3]

5. What is pandas?
Pandas is an open-source Python library used for data manipulation, analysis and
cleaning. It provides fast and flexible tools to work with tabular data, similar to
spreadsheets or SQL tables.

Before using Pandas, make sure it is installed:

pip install pandas

After the Pandas have been installed in the system we need to import the library. This
module is imported using:
import pandas as pd

6. Define series.

A Pandas Series is one-dimensional labeled array capable of holding data of any type
(integer, string, float, Python objects etc.). The axis labels are collectively called indexes.
Series is created by loading the datasets from existing storage which can be a SQL
database, a CSV file or an Excel file.
import pandas as pd
import numpy as np

s = [Link]()
print("Pandas Series: ", s)
data = [Link](['g', 'e', 'e', 'k', 's'])

s = [Link](data)
print("Pandas Series:\n", s)
Output

7. Define dataframe.

Creating a Pandas DataFrame


Pandas allows us to create a DataFrame from many data sources. We can create
DataFrames directly from Python objects like lists and dictionaries or by reading data from
external files like CSV, Excel or SQL databases.
Here are some ways by which we create a dataframe:

1. Creating DataFrame using a List


If we have a simple list of data, we can easily create a DataFrame by passing that list to the
[Link]() function.
import pandas as pd
lst = ['Geeks', 'For', 'Geeks', 'is',
'portal', 'for', 'Geeks']
df = [Link](lst)
print(df)
Output:

8. What is indexing in pandas?

Indexing in pandas refers to the methods used to select specific rows and columns from a Pandas Series
or DataFrame. It serves as an address system for your data, allowing for efficient retrieval, alignment, and
manipulation.

Core Indexing Methods


Pandas provides three primary ways to access data:

 .loc[] (Label-based Indexing): Used to select data by the labels of rows and columns.
o Inclusivity: Unlike standard Python slicing, the endpoint in .loc is included (e.g., [Link]['a':'c']
includes 'c').
o Usage: [Link][row_label, column_label].

 .iloc[] (Integer-based Indexing): Used to select data by its numerical position (0-based).
o Inclusivity: Follows standard Python/NumPy conventions where the endpoint is excluded (e.g.,
[Link][0:2] gets positions 0 and 1).
o Usage: [Link][row_position, column_position].

 [] (Square Bracket Operator): The most basic method, often used for quick column selection or row
slicing.
o Single/Multiple Columns: df['column_name'] or df[['col1', 'col2']].
o Row Slicing: df[0:5] selects the first five rows.

9. What is reindexing?
Reindexing in Pandas is used to change the row or column labels of a DataFrame to
match a new set of indices. This is useful when aligning data, adding missing labels, or
reshaping your DataFrame. If the new index includes values not present in the original
DataFrame, Pandas fills those with NaN by default. For example, if we try adding a new
row using reindex():

import pandas as pd
data = {'A': [1, 2, 3], 'B': [4, 5, 6]}
df = [Link](data)
a = [Link]([0, 1, 2, 3])
print(a)

Output
A B
0 1.0 4.0
1 2.0 5.0
2 3.0 6.0
3 NaN NaN
Index 3 wasn’t present in the original DataFrame, so it's filled with NaN.

10. What is data alignment?

Data alignment is a core feature of pandas that ensures operations between different DataFrames or
Series happen between matching labels, rather than just matching positions.

There are two ways "alignment" is usually discussed in pandas: Automatic Alignment (how pandas
behaves during math/logical operations) and the .align() method (explicitly syncing two objects). [1, 2]

1. Automatic Data Alignment


When you perform operations (like addition or subtraction) on two pandas objects, pandas automatically
aligns them by their index labels. If a label exists in one object but not the other, pandas fills the result for
that label with NaN (Not a Number) to prevent data corruption from misaligned rows. [1, 2, 3, 4, 5]

 Matching Labels: Data is combined (e.g., \(10 + 20\)).


 Missing Labels: Result becomes NaN.


2. The .align() Method
If you need to explicitly synchronize two DataFrames or Series so they share the exact same row or
column structure before performing an operation, you use the .align() method.

It returns a tuple of two new objects, both reshaped to match based on the join type:

import pandas as pd

df1 = [Link]({'A': [1, 2]}, index=['a', 'b'])


df2 = [Link]({'A': [10, 20]}, index=['b', 'c'])
# Explicitly align both to have the same indexes (outer join)
left, right = [Link](df2, join='outer')
print(left)

# Output will have indexes a, b, c (c will be NaN)

11. What is data visualization?

Data visualization uses charts, graphs and maps to present information clearly and simply. It turns
complex data into visuals that are easy to understand. With large amounts of data in every industry,
visualization helps spot patterns and trends quickly, leading to faster and smarter decisions.

Common Types of Data Visualization


1. Charts and Graphs: They are used to visualize data, with charts comparing data points across
categories or showing trends over time and graphs analyzing relationships between variables to
identify correlations, trends and outliers. Examples: Bar Charts, Line Charts, Pie Charts, Scatter
Plots, Histograms, Box Plots.
2. Maps: They are used to display geographical data which provides spatial context to trends and
patterns. Examples: Geographic Maps, Heat Maps
3. Dashboards: They combine multiple visualizations into a single interface which provides real-
time insights and interactive features for users to explore data.

12. What is matplotlib?


Matplotlib is a Python library for creating static, interactive and animated
visualizations from data. It provides flexible and customizable plotting functions that
help in understanding data patterns, trends and relationships effectively.

Let's create a simple line plot using Matplotlib, showcasing the ease with which you can
visualize data.
import [Link] as plt
x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]
[Link](x, y)
[Link]()

Output
13. What is the purpose of [Link]() command?

The main purpose of [Link]() in Python's Matplotlib library is to display all currently active figures
in a visual window. [Link]() is the command that tells the backend to open a GUI window and make
the visualization visible.

Rendering: It triggers the rendering process for all figures created up to that point in your script.

14. Differentiate between Figure and Axes in Matplotlib.

In Matplotlib, Figures and Axes are the fundamental building blocks of any visualization. Think of the
Figure as the entire window or canvas, and the Axes as the actual "plot" (the area where data is drawn).

Plot consists of at least 3 distinct layers:

1️⃣ Figure: a top level container for holding everything else.

2️⃣ Axe: a container that sits within the figure and it’s a canvas for
your actual plots.

3️⃣ Plot : the shapes that make up your visualisation. The bars, points
or lines, the legends and annotations.

15. What function is used to create subplots in Matplotlib?


subplots() function simplifies the creation of multiple plots within a single figure for
organized visualization of various datasets. Before diving into subplots, let's start with a
simple plot using [Link]():
subplots() to create two plots in a single figure.

import [Link] as plt


import numpy as np

# Plot 1:
x1 = [Link]([1, 2, 3, 4])
y1 = [Link]([10, 20, 25, 30])
[Link](1, 2, 1)
[Link](x1, y1)
# Plot 2:
x2 = [Link]([1, 2, 3, 4])
y2 = [Link]([30, 25, 20, 10])
[Link](1, 2, 2)
[Link](x2, y2)
[Link]()

Output:

16. What is a legend in a plot?

A legend is an area describing the elements of the graph. In the Matplotlib library, there’s a
function called legend() which is used to place a legend on the axes. In this article, we will
learn about the Matplotlib Legends. In this example, a simple quadratic function \( y = x^2 \)
is plotted against the x-values [1, 2, 3, 4, 5]. A legend labeled "single element" is added to
the plot, clarifying the plotted data.

import numpy as np
import [Link] as plt

x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
[Link](x, y)
[Link](['single element'])
[Link]()
Output :
17. Which function is used to annotate specific points in a plot.

Annotate any point in the chart with text using the annotate() function. The function
parameters used in the example below are:

 text : The text of the annotation


 xy : The point (x,y) to annotate
 xytext : The position (x,y) to place the text at (If None, defaults to xy)
 arrowprops : The properties used to draw an arrow between the positions xy and
xytext

18. How do you save a plot to a file in Matplotlib?

The savefig Method


With a simple chart, now we can opt to output the chart to a file
instead of displaying it (or both if desired), by using
the .savefig() method.

1In [5]: [Link]('books_read.png')

The .savefig() method requires a filename be specified as the first


argument. This filename can be a full path and as seen above, can
also include a particular file extension if desired. If no extension is
provided, the configuration value of [Link] is used instead.

12 Marks Questions
1. Explain the creation of arrays in Numpy with examples for different methods such as array(),
arange(), linspace(), and zeros().

In Python, array, arange, zeros, and linspace are core functions used primarily within the NumPy
library to create and manage numerical data structures.

[Link]()

This function converts existing Python data structures, like lists or tuples, into a NumPy ndarray.

Usage: [Link]([1, 2, 3])

 Key Feature: Creates a clone of the original object to ensure the data is stored in a contiguous block of
memory for fast mathematical operations.
[Link]()

Generates a new array of a specified shape filled entirely with zeros.

Usage: [Link]((3, 4)) creates a 3-row, 4-column matrix of zeros.

 Key Feature: Highly efficient for pre-allocating memory when you know the size of the array but haven't
calculated the values yet.
[Link]()

Creates an array with evenly spaced values within a given range, similar to Python's built-in range().

Syntax: [Link](start, stop, step)

 Key Feature: You define the step size (e.g., "give me every 2nd number"). The stop value is exclusive
by default.

 Example: [Link](0, 10, 2) results in [0, 2, 4, 6, 8].


[Link]()

Generates a specific number of evenly spaced values between a start and end point. [1, 2]

 Syntax: [Link](start, stop, num)



 Key Feature: define the total number of elements (e.g., "give me exactly 50 numbers"). The stop
value is inclusive by default.
 Example: [Link](0, 10, 5) results in [0., 2.5, 5., 7.5, 10.].

2. Describe how legnds and annotations enhance the readability of a data visualization.

Annotations are used to add notes or more information about a topic. Annotations
can be titles, legends, Arrows, bands, labels etc. Adding legends to your figures
can help to properly describe and define it. Hence, giving more clarity. Legends in
Bokeh are simple to implement. They can be basic, automatically grouped,
manually mentioned, explicitly indexed and also interactive.
Example: Basic legends
The legend_label parameter is used to add a basic label to any one of the glyph.
from [Link] import figure, output_file, show
x = [val for val in range(10)]
y = [val for val in range(0, 20, 2)]
output_file("[Link]" )
p = figure()
[Link](x, y, legend_label="My Red Line", line_color="red")
[Link](y, x, legend_label="My Orange Line",
line_color="orange")
[Link](y[::-1], x, legend_label="My Green Line",
line_color="green")
show(p)

Output:

Example 2: Automatic Grouping can be used when we want to group multiple legend
items to be grouped into one.

from [Link] import figure, output_file, show


from [Link] import ColumnDataSource

p = figure(x_range=(0.5, 2.5), y_range=(0.5, 2.5))

source = ColumnDataSource(dict(
x=[1, 1, 2, 2, 1.5],
y=[1, 2, 1, 2, 1.5],
color=['red', 'red', 'red', 'red', 'blue'],
label=['corner', 'corner', 'corner', 'corner', 'center']
))
[Link](x='x', y='y', radius=0.05, color='color',
legend_group='label', source=source)

output_file("[Link]" )

show(p)
Output:

Example 3: Interactive legends

from [Link] import figure, output_file, show


p = figure()
x = [x for x in range(1, 11)]
colors = ['red', 'green', 'blue', 'yellow']
for i in range(2, 6):
[Link](x, [val*i for val in x], line_width=2,
color=colors[i-2],
alpha=0.8, legend_label='Multiples of
{}'.format(i))
[Link] = "top_left"
[Link].click_policy = "hide"
output_file("interactive_legend.html" )
show(p)

Output:
3. Illustrate the overview of data science process.

Data Science is a systematic approach to solving data-driven problems,


involving the collection, analysis, interpretation, presentation, and
communication of data. The Data Science process is a structured
framework used to complete a data science project, and it is essential for
both business and research use cases. This article will discuss the key
steps in the Data Science process, the tools used, and the importance of
following a well-defined process.

Key Steps in the Data Science Process


Press enter or click to view image in full size

Key Steps in the Data Science Process

1. Problem Definition: Understand the business problem, its impact,


the ultimate goals for addressing it, and the relevant project plan.

2. Data Collection: Gather data from various sources, such as


databases, APIs, or web scraping.

3. Data Processing: Perform preliminary data processing, such as


handling missing values, encoding categorical variables, and scaling
numerical variables.
4. Exploratory Data Analysis (EDA): Explore the data using summary
statistics and visualizations to better understand its characteristics,
identify patterns, relationships, and outliers.

 Descriptive Statistics: Calculate basic statistics, such as mean,


median, mode, standard deviation, and variance, to summarize the
data.

 Visualizations: Create visualizations, such as bar charts, line charts,


scatter plots, and histograms, to gain insights into the data.

5. Data Cleaning: Based on the insights from EDA, clean the data by
addressing outliers, inconsistencies, and missing values.

6. Modeling: Use the cleaned and understood data to build and train
machine learning models.

7. Evaluation: Assess the performance of the models using appropriate


evaluation metrics, such as accuracy, precision, recall, and F1-score.

8. Iteration: If the model’s performance is not satisfactory, return to the


EDA step to refine the data understanding and cleaning process, and
then rebuild and retrain the models.

9. Reporting: Communicate the results of the analysis, including the


insights gained from EDA, the chosen models, and their performance.

4. Describe the process of data mining and explain its techniques.

Data mining is the extraction of useful information from large data sets, using machine learning and other
tools to discover patterns, anomalies, and insights for decision-making.

Data mining is the process of discovering useful information from an accumulation of data, often from
a data warehouse or a collection of linked data sets. Data mining can involve machine learning, statistical
analysis, and other powerful analytical tools used to sift through large sets of data to identify trends,
hidden patterns, anomalies, and relationships to support informed decision-making and planning.
The 5-step process of data mining
1. Data collection:

 Define what problem or area of inquiry you’re exploring.


 Consider what kinds of external and internal factors could be relevant to the subject of your
exploration.
 Gather raw data from various sources, including your organization’s database and external data
that are part of your operations, like field sales and service data, IoT, or social media data.

2. Data preprocessing:

 Review the data sources you’ve gathered and make sure that you have the rights to access and
use the external data, including demographics, economic data, and market intelligence, such as
industry trends and financial benchmarks from trade associations and governments; data privacy
regulations can vary significantly depending on the region and are subject to change, so this is a
crucial step.
 Engage subject matter experts to help define, categorize, and organize the data—this part of the
process is sometimes called data wrangling or data munging.
 Clean the collected data, removing duplication, inconsistencies, incomplete records, or outdated
formats.

3. Model building:

 Select relevant algorithms and techniques (such as decision trees, regression, or clustering—
more about data mining techniques below).
 Train multiple models on your preprocessed data or fine-tune their parameters to optimize
performance.
 Test model accuracy using validation techniques to ensure reliable performance on new data.
 Compare different modeling approaches and identify the best option for your specific goals.

4. Evaluation:

 Assess model reliability across key metrics such as accuracy, precision, and error rates.
 Identify potential issues such as bias, overfitting, or data quality concerns.

5. Interpretation:

 Identify which data factors have the greatest effect on predictions and outcomes—this will help
you explain key findings to the stakeholders.
 Depending on team structure, you may need to translate model findings into insights and provide
reports or visualizations that would make results clear to non-technical decision-makers and other
stakeholders across the organization.
 Formulate specific, actionable recommendations for business strategy, operations, and
processes based on the discovered patterns.
 Select relevant metrics and establish a plan to measure the effect of implementing
recommendations derived from data mining.

Data mining techniques


Classification
One common data mining technique involves the sorting of new data into predefined categories based
on patterns learned from historical data: for example, grouping customers based on whether they’re likely
to return by analyzing their shopping patterns, payment history, and engagement levels. This would not
only help distinguish important customer segments but also deepen your understanding of your customer
relationships.
Anomaly detection
Anomaly detection is especially important for goals like fraud prevention, network security, and identity
verification. For example, this data mining technique can help spot unusual credit card activity that
deviates from a customer’s typical usage, based on factors such as unexpected locations, unusual online
purchases, or uncharacteristically large amounts. But data mining methods can also help discover new
predictors that aren’t as obvious, which brings us to the next data mining technique.

Clustering
Clustering is a data mining technique aimed at discovering natural groupings based on similarities in
data rather than pre-defined assumptions (as opposed to classification), ultimately revealing hidden
patterns and relationships. In the credit card example, clustering could uncover additional flags for
suspicious activity. For instance, historic data from accounts that have suffered from fraudsters might
reveal that a statistically significant proportion of them share another similarity: perhaps, they’ve all shown
a pattern of small test purchases from a particular merchant, followed by large transactions. Then, in the
future, this pattern could be used to detect fraudulent activity in real time.

Association rules
Another key data mining technique is association rule mining: linking two seemingly unrelated events or
activities. Imagine that you’re trying to optimize product placement in a supermarket to maximize sales. It
doesn’t take data mining to speculate that, say, customers who buy diapers are also likely to buy other
baby products, such as baby wipes. But this data mining technique might discover other, less obvious,
cross-selling opportunities: perhaps, you’ll notice that customers who stock up on disposable cutlery in
the summer are also more likely to buy insect repellent and marshmallows. These products would
normally be in different product isles, but data mining might point to a seasonal shopping mission: getting
supplies for spending time outdoors. In this scenario, the association rule data mining technique would
help the retailer exploit this seasonal opportunity.

Regression
One of the mathematical data mining techniques, regression analysis predicts a number based on historic
patterns. It’s a classic tool used in many fields and contexts, including sales forecasting, stock price
predictions, and financial analysis.

5. Explain the different measures of central tendency and describe the suitable measures for the
different type of data distribution.

Central tendencies in statistics are numerical values that represent the middle or typical
value of a dataset. Also known as averages, they provide a summary of the entire data,
making it easier to understand the overall pattern or behavior. These values are useful
because they capture the essence of large datasets in a single, representative number.

Central Tendency
The three most commonly used measures of central tendency are mean, median,
and mode.

Mean
Mean in general terms is used for the arithmetic mean of the data, but other than the
arithmetic mean there are geometric mean and harmonic mean as well that are calculated
using different formulas.
The Arithmetic Mean is the most common type of average. It is obtained by adding all the
observations and then dividing by the total number of observations. It gives a simple
average value representing the entire data set.
The formula for the Arithmetic Mean is given by
xˉ=∑xiNxˉ=N∑xi
Where,
 x1, x2, x3, . . ., xn are the observations, and
 N is the number of observations.

Median of Ungrouped Data

To calculate the Median, the observations must be arranged in ascending or descending


order. If the total number of observations is N, then there are two cases
Case 1: When N is Odd
Median = Value of observation at [(n + 1) ÷ 2]th Position
When N is odd the median is calculated as shown in the image below.

Case 2: When N is Even


Median = Arithmetic mean of Values of observations at (n ÷ 2)th and [(n ÷ 2) + 1]th
Position
When N is even the median is calculated as shown in the image below.
Mode
Mode is the value of that observation which has a maximum frequency corresponding to it.
In other, that observation of the data occurs the maximum number of times in a dataset.

Mode=3

6. Explain the concept of subplots in Matplotlib with an example.

subplots() function simplifies the creation of multiple plots within a single figure for
organized visualization of various datasets. Before diving into subplots, let's start with a
simple plot using [Link]():
import [Link] as plt

[Link]([1, 2, 3, 4], [16, 4, 1, 8])


[Link]()
Output:

Plot using Python matplotlib

What is [Link]()
The subplots() function in [Link] creates a figure with a set of subplots
arranged in a grid. It allows you to easily plot multiple graphs in a single figure, making
your visualizations more organized and efficient.

Syntax
[Link](nrows=1, ncols=1)

This syntax creates a figure with nrows rows and ncols columns of subplots.

Creating Multiple Plots with subplots()

use subplots() to create two plots in a single figure.

import [Link] as plt


import numpy as np

# Plot 1:
x1 = [Link]([1, 2, 3, 4])
y1 = [Link]([10, 20, 25, 30])

[Link](1, 2, 1)
[Link](x1, y1)

# Plot 2:
x2 = [Link]([1, 2, 3, 4])
y2 = [Link]([30, 25, 20, 10])

[Link](1, 2, 2)
[Link](x2, y2)

[Link]()
Output:
Two side-by-side plots displaying different datasets.

The subplots() function in Matplotlib allows plotting multiple plots using the same data
or axes. For example, setting nrows=1 and ncols=2 creates two subplots that share the
y-axis.

import [Link] as plt


import numpy as np

x = [Link]([0, 1, 2, 3])
y = [Link]([3, 8, 1, 10])

fig, ax = [Link](1, 2)

ax[0].plot(x, y)
ax[0].set_title('Plot 1')

ax[1].plot(x, y, 'r')
ax[1].set_title('Plot 2')

[Link]()
Output:
Two side-by-side plots displaying different datasets.

Stacking Subplots in Two Directions

You can stack subplots vertically and horizontally by adjusting the nrows and ncols
parameters in subplots(). This example demonstrates a 2x2 grid layout.
# Implementation of matplotlib function
import numpy as np
import [Link] as plt

# First create some toy data:


x = [Link](0, 2 * [Link], 400)
y1 = [Link](x)
y2 = [Link](x**2)
y3 = y1**2
y4 = y2**2

fig, ax = [Link](nrows=2, ncols=2)


ax[0, 0].plot(x, y1, c='red')
ax[0, 1].plot(x, y2, c='red')
ax[1, 0].plot(x, y3, c='blue')
ax[1, 1].plot(x, y4, c='blue')

ax[0, 0].set_title('Simple plot with sin(x)')


ax[0, 1].set_title('Simple plot with sin(x**2)')
ax[1, 0].set_title('Simple plot with sin(x)**2')
ax[1, 1].set_title('Simple plot with sin(x**2)**2')

[Link]('Stacked subplots in two direction')


[Link]()

Output:
A 2x2 grid of plots, each displaying different mathematical functions.

Sharing Axes Between Subplots

In some cases, you may want your subplots to share axes. This is useful when
comparing datasets with similar ranges. By setting the sharex or sharey parameter
to True, the subplots will share their x or y axis.
Example Code for Shared Axis:

import numpy as np
import [Link] as plt

x = [Link](0, 2 * [Link], 400)


y1 = [Link](x)
y2 = [Link](x**2)

fig, (ax1, ax2) = [Link](2, sharex=True)


[Link](x, y1, c='red')
[Link](x, y2, c='red')

ax1.set_ylabel('Simple plot with sin(x)')


ax2.set_ylabel('Simple plot with sin(x**2)')

[Link]('Subplots with shared axis')


[Link]()
Output:
1. Define Data science.
Data science is the study of data used to extract meaningful insights for business
decisions. It combines mathematics, computing and domain knowledge to solve
real-world problems and uncover hidden patterns. It processes raw data to address
business challenges and predict future trends.

 Data Collection: Gathering raw data from various sources, such as databases, sensors
or user interactions.
 Data Cleaning: Ensuring the data is accurate, complete and ready for analysis.
 Data Analysis: Applying statistical and computational methods to identify patterns,
trends or relationships.
 Data Visualization: Creating charts, graphs and dashboards to present findings clearly.
 Decision-Making: Using insights to inform strategies, create solutions or predict
outcomes.

2. What is big data?


Big Data refers to vast and rapidly growing volumes of data that are too large and
complex for traditional data processing tools to manage. This data comes in many
forms structured (e.g., tables), semi-structured (e.g., JSON, XML), and
unstructured (e.g., text, images, video).

3. What is machine learning?


Machine learning is a branch of artificial intelligence that enables algorithms to
uncover hidden patterns within datasets. It allows them to predict new, similar data
without explicit programming for each task. Machine learning finds applications in
diverse fields such as image and speech recognition, natural language processing,
recommendation systems, fraud detection, portfolio optimization, and automating
tasks.

 Handles Massive Data: Machine learning works well with large data and finds patterns
that humans might miss.
 Adapts Dynamically: Systems evolve with new data, staying relevant in changing
environments.
 Drives Smarter Decisions: From predicting customer behavior to detecting fraud, ML
enhances decision-making with data-driven insights.
 Personalizes Experiences: Recommendation systems, like those on Netflix or Amazon,
tailor suggestions to individual preferences.

4. What is data mining?

Data Mining is the process of discovering meaningful patterns and insights from large
datasets using statistical, machine learning and computational techniques. It helps
organizations analyze historical data and make data-driven decisions.
 Extracts hidden patterns and relationships from large datasets
 Uses techniques such as classification, clustering and regression
 Widely used in marketing, finance, healthcare and business analytics

5. What are the characteristics of big data?

The 5 V’s of Big Data


 Volume: Refers to the huge amount of data generated every second-ranging from
terabytes to petabytes. Example: YouTube uploads 500+ hours of video every minute.
 Velocity: The speed at which data is created, shared, and processed. Data streams in
from sensors, social media, and transactions in real-time.
 Variety: Data comes in multiple formats-text, audio, images, videos, logs, sensor data,
etc. Handling all these types together is complex
 Veracity: Refers to the trustworthiness and accuracy of the data. Inconsistent,
duplicated, or noisy data can lead to wrong insights.
 Value: Not all data is useful. The key is extracting relevant data and turning it into
business value through analytics.

6. What is meant by data cleaning?

Data cleaning is the process of preparing raw data by detecting and correcting errors so it
can be effectively used for analysis. It is a foundational step in data preprocessing that
ensures datasets are suitable for analytical, statistical and machine learning tasks.
 Raw data is often noisy, incomplete and inconsistent which can negatively impact the
accuracy of the model.
 Clean datasets are also important in EDA (Exploratory Data Analysis), which enhances
the interpretability of data so that the right actions can be taken based on insights.

7. List the categories of data.

Data can be categorised in different ways depending on how it is collected, stored and
represented.

1. Quantitative Data

Quantitative data is information that can be measured, counted and expressed in numerical
form. It provides objective values that can be analyzed statistically to identify patterns,
trends and relationships.
 Represents numbers and measurable values.
 Can be divided into: Discrete data (Whole numbers) and Continuous data (Values on a
scale).
 Widely used in research, finance, engineering and business analytics.
Example: Age of people, number of customers visiting a store, temperature readings, sales
revenue.

2. Qualitative Data

Qualitative data is descriptive, non-numeric information that explains qualities,


characteristics or categories rather than quantities. It helps understand opinions,
experiences and meanings behind behaviors.
 Focuses on qualities, attributes and categories rather than numbers.
 Often collected through surveys, interviews or observations.
 Useful for understanding opinions, motivations and behaviors.
Example: Customer feedback (“satisfied”, “unsatisfied”), product colors, interview
transcripts, social media comments.

3. Structured Data

Structured data is information organized into a predefined format (rows and columns) that
makes it easily searchable and manageable by traditional databases.
 Stored in relational databases or spreadsheets.
 Easy to process with SQL and other tools.
 Best suited for tasks requiring accuracy and consistency.
Example: Bank transactions, employee records, product inventories.

4. Unstructured Data

Unstructured data is raw information that does not follow a predefined structure or format
making it harder to organize and analyze with conventional tools.
 Accounts for over 80% of data generated globally.
 Requires advanced tools (AI, NLP, computer vision) to extract insights.
 Common in social media, multimedia and IoT applications.
Example: Emails, images, videos, voice recordings, PDF documents.

5. Semi-Structured Data

Semi-structured data combines aspects of structured and unstructured data. It does not
reside in traditional tables but still contains tags or markers that provide a loose structure.
 Provides a balance between flexibility and structure.
 Easier to analyze than unstructured data, but less rigid than structured data.
 Often used in web applications, IoT devices and log systems.
Example: JSON files, XML documents, NoSQL databases, sensor logs.

8. Define data . What are the types of data?

Data is the raw form of information, a collection of facts, figures, symbols or observations
that represent details about events, objects or phenomena. By itself, data may appear
meaningless, but when organized, processed and interpreted, it transforms into valuable
insights that support decision-making, problem-solving and innovation.
 Data refers to raw facts, figures, or information that can be processed and analysed to
extract meaningful insights.
 In data science and computing, data is categorised into different types based on its
structure and nature.
 Understanding its type helps in selecting appropriate analysis and processing methods.

9. Compare Discrete and Continuous variables.

Discrete variable is a type of variable that can only take on specific or distinct values. These
values are typically whole numbers or integers. Discrete variables often represent counts or
categories.
Example of discrete variables are:
 Number of students in a classroom: It is a discrete variable because it can only take
on whole number values (e.g., 25 students, 30 students).

Continuous variable is a type of variable that can take on any value within a given range.
Unlike discrete variables, which consist of distinct, separate values, continuous variables
can represent an infinite number of possible values, including fractional and decimal values.
Continuous variables often represent measurements or quantities.
Example of continuous variables are:
 Height: Height is a continuous variable because it can take on any value within a range
(e.g., 150.5 cm, 162.3 cm, 175.9 cm).

10. What is meant by frequency distribution and its types.

A frequency distribution is a method for organizing data and determining how often each
value occurs.
 It shows how many times each value or range of values occurs in a dataset.
 Instead of examining raw, scattered numbers, this approach presents data in a
structured table or graph, making patterns, trends, and comparisons easy to identify.

To represent a frequency distribution, various methods are available, including histograms,


Bar Graphs, Frequency Polygons, and Pie Charts.

Graph Type Description Use Cases

Represents the frequency of


each interval of continuous Continuous data distribution
Histogram
data using bars of equal analysis.
width.

Represents the frequency of


each interval using bars of Comparing discrete data
Bar Graph
equal width; it can also categories.
represent discrete data.

Frequency Polygon Connects midpoints of class Comparing various


frequencies using lines,
Graph Type Description Use Cases

similar to a histogram but


datasets.
without bars.

Circular graph showing data


as slices of a circle,
Showing relative sizes of
Pie Chart indicating the proportional
data portions.
size of each slice relative to
the whole dataset.

11. Define outliers.

Outliers are data points that differ significantly from the rest of the dataset and do not
follow the general pattern. They can occur due to errors, rare events or natural variability
in data.

Outliers can occur due to a variety of reasons. Identifying their source is crucial for accurate
data analysis
 Data Entry Errors: Mistakes made while entering data manually can generate extreme
or inconsistent values.
 Measurement Errors: Faulty instruments or incorrect experimental setups can lead to
abnormally high or low readings.
 Experimental Errors: Poorly designed experiments may produce results that do not
accurately represent the underlying phenomenon.
 Intentional Outliers: Sometimes outliers are introduced deliberately such as in cases of
fraud or data manipulation.
 Data Processing Errors: Errors during data collection, cleaning or transformation can
introduce unusual values.
 Natural Variation: Some outliers arise naturally due to inherent variability in the
population or process being studied.

12. What is project charter?

Project Charter refers to a statement of objectives in a project. This statement also sets out
detailed project goals, roles and responsibilities, identifies the main stakeholders, and the level of
authority of a project manager.

It acts as a guideline for future projects as well as an important material in the organization's
knowledge management system.

The project charter is a short document that would consist of new offering request or a request
for proposal. This document is a part of the project management process, which is required by
Initiative for Policy Dialogue (IPD) and Customer Relationship Management (CRM).
Data visualization

3 Marks question answer

1. What is a scatter plot? For what type of data is scatter plot usually
used for?

A scatter plot is a chart used to plot a correlation between two or more variables at the same
time. It’s usually used for numeric data.

[Link] is Matplotlib?

Matplotlib is a cross-platform, data visualization and graphical plotting library for Python and its
numerical extension NumPy. Matplotlib is a comprehensive library for creating static, animated and
interactive visualizations in Python. Matplotlib is a plotting library for the Python programming language.
It allows to make quality charts in few lines of code. Most of the other python plotting library are build on
top of Matplotlib.

[Link] is legend?

Plot legends give meaning to a visualization, assigning labels to the various plot
elements. Legends are found in maps describe the pictorial language or symbology
of the map. Legends are used in line graphs to explain the function or the values
underlying the different lines of the graph.

4. What is use of tick?

A tick is a short line on an axis. For category axes, ticks separate each category.
For value axes, ticks mark the major divisions and show the exact point on an axis
that the axis label defines. Ticks are always the same color and line style as the
axis.
• Ticks are the markers denoting data points on axes. Matplotlib's default tick
locators and formatters are designed to be generally sufficient in many common
situations. Position and labels of ticks can be explicitly mentioned to suit specific
requirements.

5. What is Seaborn?

• Seaborn is a Python data visualization library based on Matplotlib. It provides a


high-level interface for drawing attractive and informative statistical graphics.
Seaborn is an open- source Python library.

• Seaborn helps you explore and understand your data. Its plotting functions
operate on dataframes and arrays containing whole datasets and internally perform
the necessary semantic mapping and statistical aggregation to produce informative
plots.

• Its dataset-oriented, declarative API. User should focus on what the different
elements of your plots mean, rather than on the details of how to draw them.

[Link] is data visualization and its concept?

Data visualization is the graphical representation of information and data.

Data visualization based on two concepts:

1. Each attribute of training data is visualized in a separate part of screen.

2. Different class labels of training objects are represented by different colors.


7. What is the difference between Matplotlib and seaborn.
12 Mark Question Answer

[Link] Line chart and Bar chart.

Line chart is one of the basic plots and can be created using plot() function. It is used to represent
a relationship between two data X and Y on a different axis.

Syntax:
[Link](x, y)

Parameter: x, y Coordinates for data points.


Example: This code plots a simple line chart with labeled axes and a title using Matplotlib.
import [Link] as plt

x = [10, 20, 30, 40]


y = [20, 25, 35, 55]

[Link](x, y)
[Link]("Line Chart")
[Link]('Y-Axis')
[Link]('X-Axis')
[Link]()
Output
2. Bar Chart

Bar chart displays categorical data using rectangular bars whose lengths are proportional to the
values they represent. It can be plotted vertically or horizontally to compare different categories.
Syntax:
[Link](x, height)

Parameter:
 x: Categories or positions on x-axis.
 height: Heights of the bars (y-axis values).
Example: This code creates a simple bar chart to show total bills for different days. X-axis
represents the days and Y-axis shows total bill amount.
import [Link] as plt

x = ['Thur', 'Fri', 'Sat', 'Sun']


y = [170, 120, 250, 190]

[Link](x, y)
[Link]("Bar Chart")
[Link]("Day")
[Link]("Total Bill")
[Link]()
Output

Bar Chart

2. Explain scatter plot and pie chart.

Scatter plots are used to observe relationships between variables. The scatter() method in the
matplotlib library is used to draw a scatter plot.
Syntax:
[Link](x, y)

Parameter: x, y Coordinates of the points.


Example: This code creates a scatter plot to visualize the relationship between days and total bill
amounts using scatter().
import [Link] as plt

x = ['Thur', 'Fri', 'Sat', 'Sun', 'Thur', 'Fri', 'Sat', 'Sun']


y = [170, 120, 250, 190, 160, 130, 240, 200]
[Link](x, y)
[Link]("Scatter Plot")
[Link]("Day")
[Link]("Total Bill")
[Link]()
Output

Scatter Plot

5. Pie Chart

Pie chart is a circular chart used to show data as proportions or percentages. It is created using the
pie(), where each slice (wedge) represents a part of the whole.
Syntax:
[Link](x, labels=None, autopct=None)

Parameter:
 x: Data values for pie slices.
 labels: Names for each slice.
 autopct: Format to display percentage (e.g., '%1.1f%%').
Example: This code creates a simple pie chart to visualize distribution of different car brands. Each
slice of pie represents the proportion of cars for each brand in the dataset.

import [Link] as plt


import pandas as pd
cars = ['AUDI', 'BMW', 'FORD','TESLA', 'JAGUAR',]
data = [23, 10, 35, 15, 12]
[Link](data, labels=cars)
[Link](" Pie Chart")
[Link]()
Output

Pie Chart
6. Explain histogram and Box plot.
Histogram shows the distribution of data by grouping values into bins. The hist() function is used to
create it, with X-axis showing bins and Y-axis showing frequencies.
Syntax:
[Link](x, bins=None)

Parameter:
 x: Input data.
 bins: Number of bins (intervals) to group data.

Example: This code plots a histogram to show frequency distribution of total bill values from the list
x. It uses 10 bins and adds axis labels and a title for clarity.

import [Link] as plt


x = [7, 8, 9, 10, 10, 12, 12, 12, 13, 14, 14, 15, 16, 16, 17, 18,
18, 19, 20, 20,
21, 22, 23, 24, 25, 25, 26, 28, 30, 32, 35, 36, 38, 40, 42,
44, 48, 50]
[Link](x, bins=10, color='steelblue')
[Link]("Histogram")
[Link]("Total Bill")
[Link]("Frequency")
[Link]()
Output
Histogram

Box plot

Box plot is a simple graph that shows how data is spread out. It displays the minimum, maximum,
median and quartiles and also helps to spot outliers easily.
Syntax:
[Link](x, notch=False, vert=True)

Parameter:
 x: Data for which box plot is to be drawn (usually a list or array).
 notch: If True, draws a notch to show the confidence interval around the median.
 vert: If True, boxes are vertical. If False, they are horizontal.
Example: This code creates a box plot to show the data distribution and compare three groups
using matplotlib
import [Link] as plt

data = [ [10, 12, 14, 15, 18, 20, 22],


[8, 9, 11, 13, 17, 19, 21],
[14, 16, 18, 20, 23, 25, 27] ]

[Link](data)
[Link]("Groups")
[Link]("Values")
[Link]("Box Plot")
[Link]()
Output

Box Plot
7. Explain 3 dimensional plotting.

Matplotlib is the most popular choice for data visualization. While initially developed for plotting 2-D
charts like histograms, bar charts, scatter plots, line plots, etc., Matplotlib has extended its capabilities to
offer 3D plotting modules as well.

• First import the library :

[Link] as plt

from mpl_toolkits.mplot3d import Axes3D

• The first one is a standard import statement for plotting using matplotlib, which
you would see for 2D plotting as well. The second import of the Axes3D class is
required for enabling 3D projections. It is, otherwise, not used anywhere else.

• Create figure and axes

fig = [Link](figsize=(4,4))

ax = fig.add_subplot(111, projection='3d')

Output:

Example :

fig=[Link](figsize=(8,8))
ax=[Link](projection='3d')
[Link]()
t=[Link](0,10*[Link],[Link]/50)
x=[Link](t)
y=[Link](t)
ax.plot3D(x,y,t)
ax.set_title('3D Parametric Plot')
# Set axes label
ax.set_xlabel('x',labelpad=20)
ax.set_ylabel('y', labelpad=20)
ax.set_zlabel('t', labelpad=20)
[Link]()
Output:

You might also like