[go: up one dir, main page]

0% found this document useful (0 votes)
29 views26 pages

Unit 3 & 4

Uploaded by

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

Unit 3 & 4

Uploaded by

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

1. List and explain various file opening modes with examples.

Python has 7 file opening modes:

•r - Opens the file for reading only. This is the default mode.
•w - Opens the file for writing only. If the file exists, it will be overwritten. If the
file does not exist, it will be created.
•a - Opens the file for appending. The file pointer will be placed at the end of
the file.
• r+ - Opens the file for reading and writing.
• w+ - Opens the file for writing and reading. If the file exists, it will be
overwritten. If the file does not exist, it will be created.
• a+ - Opens the file for appending and reading. The file pointer will be placed at
the end of the file.
• rb - Opens the file in binary mode for reading only.
• wb - Opens the file in binary mode for writing only. If the file exists, it will be
overwritten. If the file does not exist, it will be created.
• ab - Opens the file in binary mode for appending. The file pointer will be
placed at the end of the file.
• rb+ - Opens the file in binary mode for reading and writing.
• wb+ - Opens the file in binary mode for writing and reading. If the file exists, it
will be overwritten. If the file does not exist, it will be created.
• ab+ - Opens the file in binary mode for appending and reading. The file pointer
will be placed at the end of the file.

For example, the following code opens the file myfile.txt in read mode:

Python
with open("myfile.txt", "r") as file:
content = file.read()

print(content)

2. With program example explain how ‘with’ statement is used to open and close files

The with statement is a context manager that allows us to open and close files
automatically. The syntax for the with statement is:

Python
with open(filename, mode) as file:
# Do something with the file

The filename argument is the name of the file to open. The mode argument is the file
opening mode.

The with statement will automatically close the file when the indented block of code
is finished executing. This is useful because it helps to prevent us from forgetting to
close the file, which can lead to file corruption.

For example, the following code opens the file myfile.txt in read mode and then
prints the contents of the file:

Python
with open("myfile.txt", "r") as file:
print(file.read())

3. With code example explain any two methods to read data from the file.

There are two main methods for reading data from a file in Python:

• The read() method reads the entire contents of the file and returns it as a
string.
• The readline() method reads one line from the file and returns it as a string.

For example, the following code reads the entire contents of the file myfile.txt and
prints it to the console:

Python
with open("myfile.txt", "r") as file:
data = file.read()

print(data)

The following code reads one line from the file myfile.txt and prints it to the
console:

Python
with open("myfile.txt", "r") as file:
line = file.readline()

print(line)

4. With Code example explain any two methods to write data to the file.

There are two main methods for writing data to a file in Python:

• The write() method writes the specified data to the file.


• The writelines() method writes a list of strings to the file.

For example, the following code writes the string "Hello, world!" to the file
myfile.txt:

Python
with open("myfile.txt", "w") as file:
file.write("Hello, world!")

The following code writes a list of strings to the file myfile.txt:

Python
with open("myfile.txt", "w") as file:
file.writelines(["Hello

5. Write Python Program to Count the Occurrences of Each Word and Also Count
the Number of Words in a text File.

Python
import re

def word_count(file_name):
with open(file_name, "r") as file:
data = file.read()

words = re.split(" ", data)


counts = {}
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1

return counts

def main():
file_name = "myfile.txt"
counts = word_count(file_name)

print("The number of words in the file is:", len(counts))


for word, count in counts.items():
print(word, ":", count)

if __name__ == "__main__":
main()

This program first opens the file myfile.txt in read mode and reads the contents of
the file into a variable called data. Then, it uses the re.split() method to split the
data into a list of words. Next, it creates a dictionary called counts to store the word
counts. For each word in the list of words, it checks if the word is already in the
dictionary. If it is, it increments the count of the word. If it is not, it adds the word to
the dictionary with a count of 1. Finally, it prints the number of words in the file and
the word counts.
To run the program, you can save it as a .py file and then run it from the command
line:

Code snippet
python word_count.py

6. Explain declaring a class, defining an object and constructor with syntax and
example.

In Python, a class is declared using the class keyword. The name of the class
should be followed by a colon (:) and a block of code. The block of code can contain
attributes (variables) and methods (functions).

To define an object of a class, we use the object_name = class_name() syntax. For


example, to define an object of the Animal class, we would use the following code:

Python
class Animal:
pass

animal = Animal()

The __init__() method is the constructor of a class. It is called when an object of


the class is created. The __init__() method can be used to initialize the attributes of
the object.

For example, the following code defines a __init__() method for the Animal class:

Python
class Animal:
def __init__(self, name):
self.name = name

animal = Animal("Dog")

print(animal.name)

This code will print the following output:

Code snippet
Dog

7. What is inheritance? How to implement inheritance in Python? Give an example.

Inheritance is a way to reuse code and create new classes from existing classes. In
Python, inheritance is implemented using the inherits keyword.
To inherit from a class, we use the inherits keyword followed by the name of the
class we want to inherit from. For example, the following code defines a Dog class
that inherits from the Animal class:

Python
class Animal:
def __init__(self, name):
self.name = name

class Dog(Animal):
pass

dog = Dog("Dog")

print(dog.name)

This code will print the same output as the previous code, because the Dog class
inherits the __init__() method from the Animal class.

8. Explain with example overriding superclass constructor and method

Overriding a superclass constructor or method means to provide a new


implementation of the constructor or method in the subclass. This can be done by
defining the constructor or method with the same name in the subclass.

For example, the following code defines a Dog class that inherits from the Animal
class and overrides the __init__() method:

Python
class Animal:
def __init__(self, name):
self.name = name

class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed

dog = Dog("Dog", "Golden Retriever")

print(dog.name)
print(dog.breed)

This code will print the following output:

Code snippet
Dog
Golden Retriever

As you can see, the Dog class overrides the __init__() method from the Animal
class and provides a new implementation that takes two arguments: the name of the
dog and the breed of the dog.
9. Explain multi-level inheritance with example.

Multi-level inheritance is a type of inheritance where a class inherits from another


class that inherits from another class, and so on. For example, the following code
defines a Dog class that inherits from the Animal class, which in turn inherits from the
Object class:

Python
class Object:
pass

class Animal(Object):
pass

class Dog(Animal):
pass

dog = Dog()

print(dog.__class__)

This code will print the following output:

Code snippet
<class '__main__.Dog'>

As you can see, the dog object is an instance of the Dog class, which is an instance
of the Animal class, which is an instance of the Object class.

10. Explain multiple inheritance in Python with an example.

Multiple inheritance is a type of inheritance where a class inherits from multiple


classes. For example, the following code defines a Car class that inherits from the
Vehicle class and the Engine class:

Python
class Vehicle:
pass

class Engine:
pass

class Car(Vehicle, Engine):


pass

car = Car()

print(car.__class__)

11. Explain multipath inheritance with example.


Multipath inheritance is a type of inheritance where a class inherits from multiple
classes that are not directly related to each other. For example, the following code
defines a Car class that inherits from the Vehicle class and the Engine class:

Python
class Vehicle:
pass

class Engine:
pass

class Car(Vehicle, Engine):


pass

The Car class inherits the methods and attributes from both the Vehicle class and
the Engine class.

12. Explain method overloading and overriding with example

Method overloading is when a class has multiple methods with the same name but
different parameters. For example, the following code defines a Calculator class
that has two methods called add():

Python
class Calculator:
def add(self, a, b):
return a + b

def add(self, a, b, c):


return a + b + c

The first add() method takes two parameters, while the second add() method takes
three parameters. The method that is called will be the one that matches the number
and types of parameters that are passed to it.

Method overriding is when a subclass defines a method with the same name as a
method in its superclass. The subclass method will override the superclass method if
the method is called in an object of the subclass. For example, the following code
defines a Dog class that inherits from the Animal class:

Python
class Animal:
def speak(self):
print("I am an animal!")

class Dog(Animal):
def speak(self):
print("Woof!")

The Dog class overrides the speak() method from the Animal class. If a Dog object
calls the speak() method, the Woof! message will be printed to the console.
13. Explain the steps involved in creating a GUI application in Python with a suitable
example.

To create a GUI application in Python, you will need to use the Tkinter library. The
Tkinter library provides a set of classes and functions that you can use to create
graphical user interfaces.

The basic steps involved in creating a GUI application in Python are:

1. Import the Tkinter library.


2. Create a Tk object.
3. Create widgets (such as buttons, labels, and text boxes) and add them to
the Tk object.
4. Bind events to the widgets.
5. Start the Tk loop.

Here is an example of a simple GUI application that displays a button:

Python
import tkinter as tk

def button_clicked():
print("The button was clicked!")

root = tk.Tk()

button = tk.Button(root, text="Click Me!", command=button_clicked)


button.pack()

root.mainloop()

This code will create a Tk object and a Button widget. The Button widget will be
displayed on the Tk object. When the Button widget is clicked, the button_clicked()
function will be called. The button_clicked() function will print a message to the
console.

To run the application, you can save the code as a .py file and then run it from the
command line:

Code snippet
python my_app.py

This will open a window with the button in it. You can click the button to see the
message printed to the console.

14. How to create a button widget and bind it to the event handler? Explain with
example.
To create a button widget in Python, you can use the Tkinter library. The Tkinter
library provides a Button class that you can use to create buttons.

To bind an event handler to a button widget, you can use the bind() method. The
bind() method takes two arguments: the event type and the event handler. The
event type is the type of event that you want to bind the handler to. The event
handler is the function that you want to call when the event occurs.

Here is an example of how to create a button widget and bind it to an event handler:

Python
import tkinter as tk

def button_clicked():
print("The button was clicked!")

root = tk.Tk()

button = tk.Button(root, text="Click Me!", command=button_clicked)


button.pack()

root.mainloop()

This code will create a Tk object and a Button widget. The Button widget will be
displayed on the Tk object. When the Button widget is clicked, the button_clicked()
function will be called. The button_clicked() function will print a message to the
console.

The bind() method in the code above binds the <Button-1> event to the
button_clicked() function. The <Button-1> event is the event that occurs when the
user clicks the left mouse button on the button.

15.Write a note on arranging Widgets in a frame using layout managers

Layout managers are used to arrange widgets in a frame. There are several different
layout managers available in Tkinter, each with its own advantages and
disadvantages.

Some of the most commonly used layout managers include:

• pack(): The pack() layout manager arranges widgets in a grid. The widgets
are arranged in rows and columns, and the size of each widget is determined
by its contents.
• place(): The place() layout manager arranges widgets in absolute positions.
The position of each widget is specified by its x and y coordinates.
• grid(): The grid() layout manager is similar to the pack() layout manager, but it
gives you more control over the size and position of each widget.
• flow(): The flow() layout manager arranges widgets in a single row or column,
depending on the width or height of the frame. The widgets are arranged from
left to right or top to bottom, depending on the orientation of the frame.

The best layout manager to use depends on the specific needs of your application. If
you need to arrange widgets in a grid, the pack() layout manager is a good choice. If
you need to arrange widgets in absolute positions, the place() layout manager is a
good choice. If you need to have more control over the size and position of each
widget, the grid() layout manager is a good choice. And if you need to arrange
widgets in a single row or column, the flow() layout manager is a good choice.

Here is an example of how to use the pack() layout manager to arrange widgets in a
frame:

Python
import tkinter as tk

root = tk.Tk()

frame = tk.Frame(root)
frame.pack()

button1 = tk.Button(frame, text="Button 1")


button1.pack()

button2 = tk.Button(frame, text="Button 2")


button2.pack()

button3 = tk.Button(frame, text="Button 3")


button3.pack()

root.mainloop()

This code will create a Tk object, a Frame widget, and three Button widgets. The
Frame widget will be placed in the Tk object, and the Button widgets will be placed in
the Frame widget. The Button widgets will be arranged in a grid, with one button per
row.

To run the application, you can save the code as a .py file and then run it from the
command line:

Code snippet
python my_app.py

This will open a window with the frame and the buttons in it.

16.Explain the process of creating a Listbox widget with a suitable example. Also,
explain different values associated with selectmode option.
A listbox widget is a Tkinter widget that displays a list of items. The items in the list
can be selected by the user.

To create a listbox widget, you can use the Listbox() class. The Listbox() class
takes several arguments, but the most important ones are:

• parent: The parent widget of the listbox widget.


• height: The height of the listbox widget.
• width: The width of the listbox widget.

Here is an example of how to create a listbox widget:

Python
import tkinter as tk

root = tk.Tk()

listbox = tk.Listbox(root, height=5, width=10)


listbox.pack()

listbox.insert(0, "Item 1")


listbox.insert(1, "Item 2")
listbox.insert(2, "Item 3")

root.mainloop()

This code will create a Tk object, a Listbox widget, and three items in the listbox
widget. The listbox widget will be displayed on the Tk object. The items in the listbox
widget can be selected by the user.

The selectmode option of the Listbox() class specifies how the items in the listbox
widget can be selected. The different values that can be used for the selectmode
option are:

• single: Only one item can be selected at a time.


• browse: Multiple items can be selected by clicking and dragging the mouse.
• multiple: Multiple items can be selected by holding down the Ctrl key while
clicking on the items.

17.Write a note on

i) Text Widget

A text widget is a Tkinter widget that displays text. The text widget can be used to
display static text, or it can be used to allow the user to enter text.
To create a text widget, you can use the Text() class. The Text() class takes
several arguments, but the most important ones are:

• parent: The parent widget of the text widget.


• height: The height of the text widget.
• width: The width of the text widget.

Here is an example of how to create a text widget:

Python
import tkinter as tk

root = tk.Tk()

text = tk.Text(root, height=5, width=10)


text.pack()

text.insert(tk.INSERT, "This is some text")

root.mainloop()

This code will create a Tk object, a Text widget, and some text in the text widget. The
text widget will be displayed on the Tk object. The text in the text widget can be
edited by the user.

ii) Entry Widget

An entry widget is a Tkinter widget that allows the user to enter text. The entry
widget can be used to collect input from the user.

To create an entry widget, you can use the Entry() class. The Entry() class takes
several arguments, but the most important ones are:

• parent: The parent widget of the entry widget.


• width: The width of the entry widget.

Here is an example of how to create an entry widget:

Python
import tkinter as tk

root = tk.Tk()

entry = tk.Entry(root, width=10)


entry.pack()

entry.insert(0, "Enter some text")

root.mainloop()
This code will create a Tk object, an Entry widget, and some text in the entry widget.
The entry widget will be displayed on the Tk object. The text in the entry widget can
be edited by the user.

UNIT-4

4\6 MARKS

1. Explain four SQLite module methods required to use SQLite database.

The SQLite module provides several methods that are required to use SQLite
databases. These methods include:

• connect(): This method opens a connection to a SQLite database.


• cursor(): This method creates a cursor object that can be used to execute
queries against the database.
• execute(): This method executes a query against the database.
• fetchone(): This method fetches the next row from the results of a query.
• fetchall(): This method fetches all the rows from the results of a query.

2. Explain any four SQLite database operations with example.

The SQLite database supports several operations, including:

• Creating a table: This operation creates a new table in the database. For
example, the following code creates a table called students:
Python
import sqlite3

conn = sqlite3.connect("my_database.db")

c = conn.cursor()

c.execute("CREATE TABLE students (name text, age integer)")

conn.commit()

• Inserting data into a table: This operation inserts data into a table. For
example, the following code inserts two rows into the students table:
Python
import sqlite3

conn = sqlite3.connect("my_database.db")

c = conn.cursor()
c.execute("INSERT INTO students (name, age) VALUES ('Alice', 20)")

c.execute("INSERT INTO students (name, age) VALUES ('Bob', 21)")

conn.commit()

• Querying a table: This operation retrieves data from a table. For example, the
following code retrieves all the rows from the students table:
Python
import sqlite3

conn = sqlite3.connect("my_database.db")

c = conn.cursor()

c.execute("SELECT * FROM students")

rows = c.fetchall()

for row in rows:


print(row)

• Updating data in a table: This operation updates data in a table. For example,
the following code updates the age of the student named "Alice" to 22:
Python
import sqlite3

conn = sqlite3.connect("my_database.db")

c = conn.cursor()

c.execute("UPDATE students SET age = 22 WHERE name = 'Alice'")

conn.commit()

• Deleting data from a table: This operation deletes data from a table. For
example, the following code deletes the row where the name is "Bob":
Python
import sqlite3

conn = sqlite3.connect("my_database.db")

c = conn.cursor()

c.execute("DELETE FROM students WHERE name = 'Bob'")

conn.commit()

3. Write a Python Program to demonstrate various SQLite Database operations.

Here is a Python program that demonstrates various SQLite database operations:

Python
import sqlite3
conn = sqlite3.connect("my_database.db")

c = conn.cursor()

# Create a table
c.execute("CREATE TABLE students (name text, age integer)")

# Insert data into the table


c.execute("INSERT INTO students (name, age) VALUES ('Alice', 20)")

c.execute("INSERT INTO students (name, age) VALUES ('Bob', 21)")

conn.commit()

# Query the table


c.execute("SELECT * FROM students")

rows = c.fetchall()

for row in rows:


print(row)

# Update the data in the table


c.execute("UPDATE students SET age = 22 WHERE name = 'Alice'")

conn.commit()

# Delete data from the table


c.execute("DELETE FROM students WHERE name = 'Bob'")

conn.commit()

# Close the connection


conn.close()
Use code with caution. Learn more
content_copy

This program will create a table called students, insert two rows into the table, query
the table, update the data in the table, and delete data from the table.

4. Explain any five NumPy array attributes with syntax.

The NumPy array has several attributes that can be used to get information about
the array. These attributes include:

• ndim: This attribute returns the number of dimensions of the array.


• shape: This attribute returns the shape of the array.
• size: This attribute returns the total number of elements in the array.
• dtype: This attribute returns the data type of the array.
• itemsize: This attribute returns the size of each element in the array.
Here are some examples of how to use these attributes:

Python
import numpy as np

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

print(arr.ndim) # Prints 1

print(arr.shape) # Prints (5,)

print(arr.size) # Prints 5

print(arr.dtype) # Prints int32

print(arr.itemsize) # Prints 4

5. Explain any four NumPy array creation functions with example.

There are several NumPy array creation functions available. Here are four of the
most commonly used functions:

• array(): This function creates an array from a Python list or tuple.


• arange(): This function creates an array of evenly spaced values.
• linspace(): This function creates an array of evenly spaced values, starting
from a specified start value and ending at a specified end value.
• zeros(): This function creates an array of zeros.
• ones(): This function creates an array of ones.

Here are some examples of how to use these functions:

Python
import numpy as np

# Create an array from a list


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

# Create an array of evenly spaced values


arr = np.arange(10)

# Create an array of evenly spaced values, starting from 1 and ending at 10


arr = np.linspace(1, 10, 10)

# Create an array of zeros


arr = np.zeros(5)

# Create an array of ones


arr = np.ones(5)

These are just a few of the many NumPy array creation functions available. For more
information, you can refer to the NumPy documentation
6. Write a note on Indexing, slicing, and iterating operations on NumPy array.

NumPy arrays can be indexed, sliced, and iterated over in a similar way to Python
lists.

Indexing

Indexing is the process of accessing a single element or a sub-array from a NumPy


array. To index a NumPy array, you can use the [] operator. The [] operator takes
two arguments: the index of the element or sub-array you want to access, and the
dimension of the array you want to access.

For example, the following code will access the first element of the NumPy array arr:

Python
import numpy as np

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

print(arr[0])

This code will print the number 1.

Slicing

Slicing is the process of accessing a sub-array from a NumPy array. To slice a


NumPy array, you can use the [start:end] operator. The [start:end] operator
takes two arguments: the start index of the sub-array you want to access, and the
end index of the sub-array you want to access.

For example, the following code will access the sub-array of arr starting from the
second element to the fourth element:

Python
import numpy as np

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

print(arr[1:4])

This code will print the numbers 2, 3, and 4.

Iterating

Iterating is the process of accessing each element in a NumPy array one at a time.
To iterate over a NumPy array, you can use the for loop.
For example, the following code will iterate over the NumPy array arr and print each
element:

Python
import numpy as np

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

for i in arr:
print(i)

This code will print the numbers 1, 2, 3, 4, and 5.

7. Explain basic arithmetic operations on NumPy array with examples.

NumPy arrays support a variety of basic arithmetic operations, including:

• Addition: +
• Subtraction: -
• Multiplication: *
• Division: /
• Modulus: %
• Exponentiation: **

For example, the following code will add the two NumPy arrays arr1 and arr2:

Python
import numpy as np

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


arr2 = np.array([6, 7, 8, 9, 10])

print(arr1 + arr2)

This code will print the following array:

Code snippet
[7 9 11 13 15]
Sure, here are the answers to your questions:

8. With code examples explain creating pandas series using Scalar data and
Dictionary.
A Pandas Series is a one-dimensional labeled array that can hold any data type. It is
similar to a NumPy array, but it has an index that associates each element with a
label.

To create a Pandas Series from scalar data, you can use the Series() constructor.
The Series() constructor takes two arguments: the data and the index. The data
can be any Python object, and the index can be any sequence of objects.
For example, the following code will create a Pandas Series from the scalar data 1:
Python
import numpy as np
import pandas as pd

data = 1

series = pd.Series(data, index=["scalar"])

print(series)

This code will print the following Pandas Series:

Code snippet
0 1
dtype: int64
To create a Pandas Series from a dictionary, you can use the Series() constructor.
The Series() constructor takes two arguments: the dictionary and the index. The
dictionary can be any Python dictionary, and the index can be any sequence of
objects.
For example, the following code will create a Pandas Series from the dictionary {1:
"one", 2: "two", 3: "three"}:
Python
import numpy as np
import pandas as pd

data = {1: "one", 2: "two", 3: "three"}

series = pd.Series(data, index=[1, 2, 3])

print(series)

This code will print the following Pandas Series:

Code snippet
0 one
1 two
2 three
dtype: object
9. Explain any four string processing methods supported by Pandas Library with
example.

Pandas provides a number of string processing methods that can be used to


manipulate and analyze strings. Here are four examples:

• str.lower(): This method converts a string to lowercase.


• str.upper(): This method converts a string to uppercase.
• str.len(): This method returns the length of a string.
• str.split(): This method splits a string into a list of substrings.
For example, the following code will convert the string "Hello World" to lowercase
and then print the length of the lowercase string:
Python
import numpy as np
import pandas as pd

string = "Hello World"

lower_string = string.lower()

print(len(lower_string))
This code will print the number 11, which is the length of the lowercase string "hello
world".

Here are some other string processing methods supported by Pandas:

• str.strip(): This method removes whitespace from the beginning and end
of a string.
• str.replace(): This method replaces a substring in a string with another
substring.
• str.find(): This method returns the index of the first occurrence of a
substring in a string.
• str.rfind(): This method returns the index of the last occurrence of a
substring in a string.
10.Explain with example any two methods of creating DataFrame.

A Pandas DataFrame is a two-dimensional labeled array that can hold any data type.
It is similar to a NumPy array, but it has an index that associates each row with a
label and a column that associates each column with a label.
There are several ways to create a Pandas DataFrame. Here are two examples:

• From a list of lists: This method creates a DataFrame from a list of lists. The
lists must have the same length, and each list must contain the same number
of elements.
• From a dictionary of lists: This method creates a DataFrame from a dictionary
of lists. The keys of the dictionary are the column names, and the values of
the dictionary are the lists of data for each column.

For example, the following code will create a DataFrame from a list of lists:

Python
import numpy as np
import pandas as pd

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

df = pd.DataFrame(data, columns=["a", "b", "c"])

print(df)
Sure, here are the answers to your questions:

11.Explain any five operations on Dataframe with example.

Here are five operations on DataFrame with example:

• Selecting columns: This operation selects a subset of columns from a


DataFrame. For example, the following code will select the columns "a" and
"b" from the DataFrame df:
Python
import numpy as np
import pandas as pd

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

df = pd.DataFrame(data, columns=["a", "b", "c"])

selected_df = df[["a", "b"]]

print(selected_df)

This code will print the following DataFrame:


Code snippet
a b
0 1 2
1 4 5
2 7 8
• Filtering rows: This operation filters a DataFrame based on a condition. For
example, the following code will filter the DataFrame df to only include rows
where the value in the "a" column is greater than 5:
Python
filtered_df = df[df["a"] > 5]

print(filtered_df)

This code will print the following DataFrame:

Code snippet
a b c
2 7 8
• Adding columns: This operation adds a new column to a DataFrame. For
example, the following code will add a column named "d" to the DataFrame
df and set the values in the column to the square of the values in the "a"
column:
Python
df["d"] = df["a"] ** 2

print(df)

This code will print the following DataFrame:

Code snippet
a b c d
0 1 2 1 1
1 4 5 9 16
2 7 8 49 64
• Summarizing data: This operation summarizes the data in a DataFrame. For
example, the following code will calculate the mean, standard deviation,
minimum, and maximum values of the values in the "a" column of the
DataFrame df:
Python
summary_df = df["a"].describe()

print(summary_df)

This code will print the following DataFrame:


Code snippet
count 3.000000
mean 5.000000
std 2.236068
min 1.000000
25% 3.250000
50% 5.000000
75% 6.750000
max 7.000000
• Merging DataFrames: This operation merges two DataFrames together. For
example, the following code will merge the DataFrames df1 and df2 together
based on the values in the "a" column:
Python
df1 = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
df2 = pd.DataFrame({"a": [4, 5, 6], "c": [7, 8, 9]})

merged_df = pd.merge(df1, df2, on="a")

print(merged_df)

This code will print the following DataFrame:

Code snippet
a b c
0 1 4 7
1 4 5 8
2 5 6 9

12.Explain Bar Graph creation using Matplot Library module.

1. Import the Matplot Library module.

2. Create a figure object.

3. Create a bar object using the bar() function. The bar() function takes two
arguments: the data and the labels. The data is the list of values that you want
to plot, and the labels are the list of labels that you want to use for the bars.
4. Add the bar object to the figure object.

5. Set the title of the figure.

6. Set the x-axis label.

7. Set the y-axis label.

8. Show the figure.


Here is an example of how to create a bar graph using the Matplot Library module:

Python
import matplotlib.pyplot as plt

# Create a figure object


fig = plt.figure()

# Create a bar object


data = [10, 20, 30, 40]
labels = ["Bar 1", "Bar 2", "Bar 3", "Bar 4"]
bar = plt.bar(labels, data)

# Add the bar object to the figure object


fig.add_subplot(111)
fig.add_bar(bar)

# Set the title of the figure


plt.title("Bar Graph")

# Set the x-axis label


plt.xlabel("Labels")

# Set the y-axis label


plt.ylabel("Values")

# Show the figure


plt.show()
This code will create a bar graph of the values in the list data. The labels for the bars
are in the list labels. The title of the figure is "Bar Graph". The x-axis label is
"Labels". The y-axis label is "Values". The figure will be shown in a pop-up window.
Sure, here are the Python programs to display a histogram, a pie chart, and a line
graph:

13. Write a program to display a histogram.


Python
import matplotlib.pyplot as plt

# Create a list of data


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

# Create a histogram
plt.hist(data)

# Set the title of the figure


plt.title("Histogram")

# Set the x-axis label


plt.xlabel("Data")

# Set the y-axis label


plt.ylabel("Frequency")

# Show the figure


plt.show()
This code will create a histogram of the values in the list data. The title of the figure
is "Histogram". The x-axis label is "Data". The y-axis label is "Frequency". The figure
will be shown in a pop-up window.

14. Write a Python program to display a pie chart showing percentage of employees
in each department. Assume there are 4 departments namely Sales, Production, HR
and Finance.
Python
import matplotlib.pyplot as plt

# Create a list of departments and the number of employees in each


department
departments = ["Sales", "Production", "HR", "Finance"]
employees = [100, 200, 300, 400]

# Calculate the percentage of employees in each department


percentages = []
for i in range(len(departments)):
percentage = employees[i] / sum(employees) * 100
percentages.append(percentage)

# Create a pie chart


plt.pie(percentages, labels=departments)

# Set the title of the figure


plt.title("Employees by Department")

# Show the figure


plt.show()

This code will create a pie chart showing the percentage of employees in each
department. The title of the figure is "Employees by Department". The pie chart will
be shown in a pop-up window.

15. Write a Python Program to create a Line Graph showing number of students of a
college in various Years. Consider 8 years data.
Python
import matplotlib.pyplot as plt
# Create a list of years
years = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017]

# Create a list of number of students in each year


students = [100, 120, 150, 180, 200, 250, 300, 350]

# Create a line graph


plt.plot(years, students)

# Set the title of the figure


plt.title("Number of Students by Year")

# Set the x-axis label


plt.xlabel("Year")

# Set the y-axis label


plt.ylabel("Number of Students")

# Show the figure


plt.show()

This code will create a line graph showing the number of students in a college in
various years. The title of the figure is "Number of Students by Year". The x-axis
label is "Year". The y-axis label is "Number of Students". The line graph will be
shown in a pop-up window.

You might also like