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

unit 4 python

The document provides a comprehensive guide on using SQLite and NumPy in Python, including how to connect to an SQLite database, create tables, insert and update data, and perform various operations. It also explains the basics of NumPy, including array creation, attributes, and functions for data manipulation. Additionally, it covers data visualization concepts and libraries such as Matplotlib and Pandas for data analysis.

Uploaded by

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

unit 4 python

The document provides a comprehensive guide on using SQLite and NumPy in Python, including how to connect to an SQLite database, create tables, insert and update data, and perform various operations. It also explains the basics of NumPy, including array creation, attributes, and functions for data manipulation. Additionally, it covers data visualization concepts and libraries such as Matplotlib and Pandas for data analysis.

Uploaded by

pujarinidhi3
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

2m:

1. How to connect to the SQLite database ? Give example

To use SQLite3 in Python, first we have to import the sqlite3 module and then create a connection
object. Connection object allows to connect to the database and will let us execute the SQL
statements. To connect to an SQLite database in Python, you can use the connect() method from the
sqlite3 module. Here is an example:

import sqlite3

conn = sqlite3.connect('example.db')
This will create a new file with the name ‘mydatabase.db’.

2. Write SQL code to create table in SQLite database.


To create a table in SQLite3, you can use the Create Table query in the execute() method.

import sqlite3
con = sqlite3.connect('mydatabase.db')
cursorObj = con.cursor()
cursorObj.execute('''CREATE TABLE movie(title text, year int, score real)''')
con.commit()
con.close()

3. Write SQL code to insert data in SQLite table..

To insert data in a table, we use the INSERT INTO statement. Consider the following line of code:

import sqlite3
con = sqlite3.connect('mydatabase.db')
cursorObj = con.cursor()
cursorObj.execute('''CREATE TABLE movie(title text, year int, score real)''')
cursorObj.execute('''INSERT INTO movie VALUES ("Titanic",1997, 9.5)''')
con.commit()
con.close()

4. Write SQL code to update SQLite table.

To update the table, simply create a connection, then create a cursor object using the connection
and finally use the UPDATE statement in the execute() method.

import sqlite3
con = sqlite3.connect('mydatabase.db')
cursorObj = con.cursor()
cursorObj.execute("UPDATE MOVIE SET SCORE=10 WHERE TITLE='Dil' ")
con.commit()
con.close()

5. What is NumPy in Python ? Give any two uses of NumPy.

NumPy is the fundamental package for scientific computing with Python. It stands for
“Numerical Python.” It supports: N-dimensional array object and Broadcasting functions

 Data analysis: NumPy arrays can be used to store and manipulate large amounts of data. This
makes it useful for a variety of data analysis tasks, such as statistical analysis, machine
learning, and data visualization.

 Scientific computing: NumPy arrays can be used to perform a wide variety of mathematical
operations, such as matrix multiplication, Fourier transforms, and differential equations.
6. Give Python code to create NumPy array using array function.

To create a NumPy array using the array function, you need to import the numpy module

import numpy as np
my_array = np.array([1, 2, 3, 4, 5])
print(my_array) #[1 2 3 4 5]
7. How to create two-dimensional arrays using NumPy

To create a two-dimensional array using NumPy, you can use the array function and pass a nested list
as an argument.

import numpy as np
my_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(my_array)
output:[[1 2 3]
[4 5 6]
[7 8 9]]
8. List any four NumPy array attributes.

ndarray.ndim

ndarray.shape

ndarray.size

ndarray.dtype

ndarray.itemsize.
ndarray.data
9. Give syntax and example for NumPy arrange() function

The NumPy arrange() function is used to create an array with evenly spaced values within a given
interval. The syntax for the arrange() function is as follows:

Syntax: np.arange([start,]stop, [step,][dtype=None])

Eg: import numpy as np


array = np.arange(1, 11)
print(array) #[ 1 2 3 4 5 6 7 8 9 10]
10.What is Pandas Library ?
pandas is a Python library that provides fast, flexible, and expressive data structures designed to
make working with “relational” or “labeled” data both easy and intuitive. It aims to be the
fundamental high-level building block for doing practical, real world data analysis in Python. The two
primary data structures of pandas, Series (one-dimensional) and DataFrame

11.What is Padas Series ? Give example.

Pandas Series is a one-dimensional labeled array capable of holding data of any type (integer, string,
float, python objects, etc.). The axis labels are collectively called indexes.
Syntax: s = pd.Series(data, index=None)

Eg: import pandas as pd

my_series = pd.Series([10, 20, 30, 40, 50])


print(my_series)
output:
0 10
1 20
2 30
3 40
4 50
dtype: int64
12.Write Python code to create Dataframe from a dictionary and display its contents.

To create a DataFrame from a dictionary and display its contents, you can use the
pandas.DataFrame() function. Each key in the dictionary will represent a column name, and the
corresponding values will be the data for that column.

import pandas as pd
data = {
'Name': ['John', 'Emily', 'Sam', 'Jessica'],
'Age': [25, 28, 31, 27],
'City': ['New York', 'London', 'Paris', 'Sydney']
}
# Create a DataFrame from the dictionary
df = pd.DataFrame(data)
print(df)
output: Name City
0 John New York
1 Emily London
2 Sam Paris
3 Jessica Sydney
13.Write Python code to create Dataframe from a tuple and display its contents.
to create a DataFrame from a tuple and display its contents, you can use the pandas.DataFrame()
function. Each element in the tuple will represent a row in the DataFrame.

import pandas as pd
data = (
('John', 25, 'New York'),
('Jessica', 27, 'Sydney')
)
# Create a DataFrame from the tuple
df = pd.DataFrame(data, columns=['Name', 'Age', 'City'])
print(df)
Name Age City

0 John 25 New York

1 Jessica 27 Sydney

14.What is Pandas DataFame ? How it is created ?

A Pandas DataFrame is a two-dimensional labeled data structure that represents a table-like data
object. It consists of rows and columns, similar to a spreadsheet or a SQL table. DataFrames are a
core data structure in the Pandas library and provide a powerful and flexible way to work with
structured data.

import pandas as pd
data = {

'Name': ['John', 'Emily', 'Sam', 'Jessica'],


'City': ['New York', 'London', 'Paris', 'Sydney']
}
# Create a DataFrame from the dictionary
df = pd.DataFrame(data)
print(df)
Name City

0 John New York


1 Emily London

2 Sam Paris
3 Jessica Sydney

15.Give the Python code to create dataframe from .csv file

To create a DataFrame from a .csv file in Python, you can use the pandas.read_csv() function from
the Pandas library.

import pandas as pd

# Read the .csv file into a DataFrame

df = pd.read_csv('data.csv')

print(df)

16.How to add new column to daataframe ?

The assign() method takes a dictionary as its argument, where the keys are the names of the new
columns and the values are the data values. For example, the following code adds a new column
named Gender to the DataFrame df:
import pandas as pd

df = pd.DataFrame({'Name': ['John Doe', 'Jane Doe', 'John Smith'], 'Age': [30, 25, 40]})
df = df.assign(Gender = ['M', 'F', 'M'])

print(df)

Name Age Gender

0 John Doe 30 M

1 Jane Doe 25 F

2 John Smith 40 M

17.Give the Python code to create datafram from Excel file.

To create a DataFrame from an Excel file in Python, you can use the pandas.read_excel() function
from the Pandas library.
import pandas as pd
# Read the Excel file into a DataFrame

df = pd.read_excel('data.xlsx', sheet_name='Sheet1')

# Display the contents of the DataFrame

print(df)

18.Give Python code to find maximum and minimum values for particular column of dataframe.

import pandas as pd
df = pd.DataFrame({'Name': ['John', 'Emily', 'Sam'],

'Age': [25, 28, 31],

'Salary': [50000, 60000, 70000]})

max_salary = df['Salary'].max()
min_salary = df['Salary'].min()

print("Maximum Salary:", max_salary)

print("Minimum Salary:", min_salary)

Maximum Salary: 70000

Minimum Salary: 50000

19.What is Data Visualization ?


Data visualization is the process of transforming data into a visual format, such as a chart, graph, or
map. It is used to communicate information clearly and effectively. Data visualization can be used to
explore data, identify patterns, and make predictions. Data visualization provides a good, organized
pictorial representation of the data which makes it easier to understand, observe, analyze.
such libraries.

 Matplotlib
 Seaborn

 Bokeh

 Plotly

20.What is matplotlib and pyplot ?

Matplotlib is an easy-to-use, low-level data visualization library that is built on NumPy arrays. It
consists of various plots like scatter plot, line plot, histogram, etc. Matplotlib provides a lot of
flexibility.

Pyplot is a sub-module of Matplotlib that provides a simple interface for creating basic plots and
graphs. It is a collection of functions that allow you to create plots quickly and easily. Pyplot is
typically imported as plt in Python scripts and is commonly used in conjunction with Matplotlib.
Pyplot provides functions for creating common types of plots, such as line plots, scatter
plots, bar plots, histograms, pie charts, and more.

4m:

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

2. Explain any four SQLite database operations with example.


I. Creating and connecting to Database

When you create a connection with SQLite, that will create a database file automatically if it
doesn’t already exist. This database file is created on disk with the connect function.

Following Python code shows how to connect to an existing database. If the database does not

exist, then it will be created and finally a database object will be returned.

import sqlite3
conn = sqlite3.connect('test.db')
print ("Opened database successfully")

Output: Opened database successfully

II. Create Table

To create a table in SQLite3, you can use the Create Table query in the execute() method.

Consider the following steps:

1. Create a connection object.


2. From the connection object, create a cursor object.

3. Using the cursor object, call the execute method with create table query as the

parameter.

import sqlite3
con = sqlite3.connect('mydatabase.db')

cursorObj = con.cursor()

cursorObj.execute('''CREATE TABLE movie(title text, year int, score real)''')

con.commit()

con.close()

In the above code, it establishes a connection and creates a cursor object to execute the create
table statement.The commit() method saves all the changes we make.

III. Insert in Table


To insert data in a table, we use the INSERT INTO statement. Consider the following line of

code:

import sqlite3
con = sqlite3.connect('mydatabase.db')
cursorObj = con.cursor()
cursorObj.execute('''CREATE TABLE movie(title text, year int, score real)''')
cursorObj.execute('''INSERT INTO movie VALUES ("Titanic",1997, 9.5)''')
con.commit()
con.close()

IV. Update Table

To update the table, simply create a connection, then create a cursor object using the connection
and finally use the UPDATE statement in the execute() method.
Suppose that we want to update the score with the movie title Dil. For updating, we will use

the UPDATE statement and for the movie whose title equals Dil. We will use the WHERE

clause as a condition to select this employee.

Consider the following code:

import sqlite3
con = sqlite3.connect('mydatabase.db')
cursorObj = con.cursor()

cursorObj.execute("UPDATE MOVIE SET SCORE=10 WHERE TITLE='Dil' ")


con.commit()
con.close()

VI. Delete

In SQLite database we use the following syntax to delete data from a table:

DELETE FROM table_name [WHERE Clause]


• Import the required module.

• Create a connection object with the database using to connect().

• Create a Cursor object by calling the cursor().

• Finally, use execute() method by passing a DELETE statement as a parameter to it.

import sqlite3
con = sqlite3.connect('mydatabase.db')
cursorObj = con.cursor()
cursorObj.execute("Delete from movie where title='Titanic' ")
con.commit()
con.close()
VII. Drop table

You can drop/delete a table using the DROP statement. The syntax of the DROP statement is
as follows:

drop table table_name

To drop a table, the table should exist in the database. Therefore, it is recommended to use “if

exists” with the drop statement as follows:

drop table if exists table_name


For example,

import sqlite3

con = sqlite3.connect('mydatabase.db')
cursorObj = con.cursor()
cursorObj.execute(" DROP TABLE IF EXISTS MOVIE ")
con.commit()
con.close()
3. Write a Python Program to demonstrate various SQLite Database operations.
4. Explain any five NumPy array attributes with syntax.
Sure! Here are five commonly used NumPy array attributes along with their syntax:

1. `shape`: Returns the dimensions of the array, i.e., the size of each dimension.

Syntax: `ndarray.shape`

Example:

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

print(arr.shape) # Output: (2, 3)


2. `dtype`: Returns the data type of the array elements.

Syntax: ndarray.dtype`
Example:

import numpy as np

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

print(arr.dtype) # Output: int64

3. `size`: Returns the total number of elements in the array.

Syntax: `ndarray.size`

Example:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])

print(arr.size) # Output: 6

4. `ndim`: Returns the number of dimensions (axes) of the array.

Syntax: `ndarray.ndim`

Example:

import numpy as np
arr = np.array([1, 2, 3])

print(arr.ndim) # Output: 1

5. `itemsize`: Returns the size (in bytes) of each element in the array.

Syntax: `ndarray.itemsize`
Example:

import numpy as np

arr = np.array([1, 2, 3], dtype=np.float64)

print(arr.itemsize) # Output: 8 (float64 takes 8 bytes)

6. data : Gives the buffer containing the actual elements of the array

Syntax: ndarray.data
import numpy as np

array_attributes = np.array([[1, 2, 3], [5, 6, 7]])


print(array_attributes.data) #output: <memory at 0x000001706B864860>

5. Explain any four NumPy array creation functions with example

1. `np.array()`: Creates an array from a Python list or tuple.


Example:

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

print(arr1) # Output: [1 2 3 4 5]

2. `np.zeros()`: Creates an array filled with zeros.

Example:

import numpy as np

zeros1 = np.zeros(5)

print(zeros1) # Output: [0. 0. 0. 0. 0.]


eg: # Create a 2D array filled with zeros

zeros2 = np.zeros((3, 4))

print(zeros2) # Output: [[0. 0. 0. 0.]

# [0. 0. 0. 0.]

# [0. 0. 0. 0.]]

3. `np.ones()`: Creates an array filled with ones.


Example:

import numpy as np

# Create a 1D array filled with ones

ones1 = np.ones(3)
print(ones1) # Output: [1. 1. 1.]

# Create a 2D array filled with ones

ones2 = np.ones((2, 4))

print(ones2) # Output: [[1. 1. 1. 1.]

# [1. 1. 1. 1.]]

4. `np.arange()`: Creates an array with evenly spaced values within a specified range.
Example:

import numpy as np
arr1 = np.arange(5)

print(arr1) # Output: [0 1 2 3 4]

5.np.linspace(): Creates an array with evenly spaced values within a specified interval.
Example:

import numpy as np
arr = np.linspace(0, 1, 5) # Creates an array with 5 values from 0 to 1 (inclusive)

print(arr) # Output: [0. 0.25 0.5 0.75 1. ]

6.numpy.random.random(): Creates an array of random values between 0 and 1 from a uniform


distribution.

Example:

import numpy as np

arr = np.random.rand(3)
print(arr) # Output: [0.15073463 0.99907448 0.17880594]

 eye() : This function creates an identity matrix. The shape argument specifies
the shape of the matrix.
import numpy as np
array = np.eye(3)
print(array) # Output: [[1. 0. 0.]
# [0. 1. 0.]
# [0. 0. 1.]]

6. Write a note on Indexing, slicing, and iterating operations on NumPy array.

Indexing is used to access individual elements or subarrays of a NumPy array. The index can be a
single integer, a tuple of integers, or a slice object.
import numpy as np
array = np.array([1, 2, 3, 4, 5])
print(array[0]) # Output: 1
print(array[1:3]) # Output: [2 3]
print(array[slice(2, 4)]) # Output: [3 4]
Slicing is used to extract a subarray from a NumPy array. The slice object is created using the :
operator. The start and end indices are optional, and if they are not specified, the entire dimension is
sliced. The step size is also optional, and if it is not specified, the default step size of 1 is used.

import numpy as np
array = np.array([1, 2, 3, 4, 5])
print(array[1:]) # Output: [2 3 4 5]
print(array[:3]) # Output: [1 2 3]

print(array[::2]) # Output: [1 3 5]
Iterating is used to iterate over the elements of a NumPy array. The for loop can be used to iterate
over the elements of a NumPy array. The enumerate() function can be used to iterate over the
elements of a NumPy array and get the index of each element.

import numpy as np
array = np.array([1, 2, 3, 4, 5])
for element in array:
print(element)
for index, element in enumerate(array):
print(index, element)
output:1
2
3

0 1

1 2

2 3

3 4

4 5

7. Explain basic arithmetic operations on NumPy array with examples

Addition : The + operator is used to add two NumPy arrays. The arrays must have the same shape, or
they will be broadcasted.

import numpy as np
array1 = np.array([1, 2, 3, 4, 5])
array2 = np.array([6, 7, 8, 9, 10])
print(array1 + array2) # Output: [7 9 11 13 15]
Subtraction : The - operator is used to subtract two NumPy arrays. The arrays must have the same
shape, or they will be broadcasted.

import numpy as np
array1 = np.array([1, 2, 3, 4, 5])
array2 = np.array([6, 7, 8, 9, 10])
print(array1 - array2) # Output: [-5 -5 -5 -5 -5]
Multiplication : The * operator is used to multiply two NumPy arrays. The arrays must have the same
shape, or they will be broadcasted.

import numpy as np
array1 = np.array([1, 2, 3, 4, 5])
array2 = np.array([6, 7, 8, 9, 10])
print(array1 * array2) # Output: [6 14 24 36 50]
Division : The / operator is used to divide two NumPy arrays. The arrays must have the same shape,
or they will be broadcasted.

import numpy as np
array1 = np.array([10, 20, 30, 40, 50])
array2 = np.array([5, 5, 5, 5, 5])
print(array1 / array2) # Output: [ 2. 4. 6. 8. 10.]
Exponentiation : The ** operator is used to raise a NumPy array to a power. The arrays must have
the same shape, or they will be broadcasted.

import numpy as np
array1 = np.array([1, 2, 3, 4, 5])
print(array1 ** 2) # Output: [1 4 9 16 25]
Modulo : The % operator is used to find the remainder when a NumPy array is divided by another
number. The arrays must have the same shape, or they will be broadcasted.

import numpy as np
array1 = np.array([1, 2, 3, 4, 5])
print(array1 % 2) # Output: [1 0 1 0 1]
8. With code examples explain creating pandas series using Scalar data and Dictionary.

the Pandas Series created from scalar data has a single column and a single row. The Pandas Series
created from dictionary has two columns and a single row. The column names are the keys of the
dictionary, and the values are the values of the dictionary.
1. Creating a Pandas Series using Scalar data:

import pandas as pd
series_scalar = pd.Series(5)
print(series_scalar)
Output:
0 5

dtype: int64

In this example, a Pandas Series is created with a single scalar value of 5. The output shows the
index as 0 and the value as 5.
2. Creating a Pandas Series using a Dictionary:

import pandas as pd
dictionary = {'a': 1, 'b': 2, 'c': 3}
series_dict = pd.Series(dictionary)
print(series_dict)
Output:

a 1

b 2

c 3

dtype: int64
In this example, a Pandas Series is created from a dictionary where keys represent the index labels
and values represent the corresponding data. The output shows the index labels ('a', 'b', 'c') along
with their respective values (1, 2, 3).
In both cases, Pandas Series provide a one-dimensional labeled array-like structure that can hold
various data types. The Series created using scalar data has a default index starting from 0, while the
Series created using a dictionary uses the dictionary keys as index labels.

9. Explain any four string processing methods supported by Pandas Library with example.

1. `str.upper()` and `str.lower()`:

- `str.upper()` converts all characters in a string to uppercase.

- `str.lower()` converts all characters in a string to lowercase.

import pandas as pd
series = pd.Series(['Hello', 'World'])
upper_case = series.str.upper()
print(upper_case)
# Output:

# 0 HELLO
# 1 WORLD

# dtype: object
lower_case = series.str.lower()

print(lower_case)

# Output:
# 0 hello

# 1 world
# dtype: object

2. `str.len()`: returns the length of each string element in a series.

import pandas as pd
series = pd.Series(['apple', 'banana', 'cherry'])
length = series.str.len()
print(length)
# Output:

#0 5

#1 6

#2 6
# dtype: int64
3. `str.replace()`:replaces a specified substring with another substring in each string element of a
series.

import pandas as pd
series = pd.Series(['Hello, world!', 'Goodbye, world!'])
replaced = series.str.replace('world', 'universe')
print(replaced)
# Output:

# 0 Hello, universe!
# 1 Goodbye, universe!

# dtype: object

4. `str.split()`:splits each string element into a list of substrings based on a specified delimiter.

import pandas as pd
series = pd.Series(['apple,banana,cherry', 'orange,grape'])
splitted = series.str.split(',')
print(splitted)
# Output:

# 0 [apple, banana, cherry]

#1 [orange, grape]
# dtype: object

5. `str.startswith()` and `str.endswith()`:

- `str.startswith()` checks if each string element starts with a specified substring.

- `str.endswith()` checks if each string element ends with a specified substring.

import pandas as pd
series = pd.Series(['apple', 'banana', 'cherry'])
starts_with_a = series.str.startswith('a')

print(starts_with_a)
# Output:
#0 True

# 1 False

# 2 False

# dtype: bool
ends_with_y = series.str.endswith('y')

print(ends_with_y)

# Output:

# 0 False

#1 True

# 2 False
# dtype: bool

6. `str.strip()`:removes leading and trailing whitespace characters from each string element in a
series.

import pandas as pd
series = pd.Series([' apple ', ' banana ', ' cherry '])
stripped = series.str.strip()
print(stripped)
# Output:
#0 apple

# 1 banana
# 2 cherry

# dtype: object
10.Explain with example any two methods of creating DataFrame

1. Creating a DataFrame from a NumPy array:

import pandas as pd
import numpy as np
data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
df = pd.DataFrame(data, columns=['A', 'B', 'C'])
print(df)
Output:

A B C

0 1 2 3

1 4 5 6

2 7 8 9
2. Creating a DataFrame from a dictionary:

import pandas as pd

data = {'Name': ['John', 'Emma', 'Mike'],


'Age': [25, 30, 35],
'City': ['New York', 'London', 'Paris']}
df = pd.DataFrame(data)
print(df)
Output:

Name Age City

0 John 25 New York


1 Emma 30 London

2 Mike 35 Paris
3. Creating a DataFrame from a CSV file:

import pandas as pd
df = pd.read_csv('data.csv')
print(df)
Assuming the 'data.csv' file contains the following data:
Name,Age,City

John,25,New York
Emma,30,London

Mike,35,Paris

Output:

Name Age City

0 John 25 New York

1 Emma 30 London
2 Mike 35 Paris

4. Creating an empty DataFrame and adding columns later:

import pandas as pd
df = pd.DataFrame()
df['Name'] = ['John', 'Emma', 'Mike']
df['Age'] = [25, 30, 35]
df['City'] = ['New York', 'London', 'Paris']
print(df)
Output:

Name Age City


0 John 25 New York

1 Emma 30 London

2 Mike 35 Paris

These are just a few methods of creating a DataFrame in Pandas. Depending on the data source and
structure, Pandas provides various ways to create and manipulate DataFrames to suit different data
analysis and manipulation tasks.

5..From a list of lists : This method creates a DataFrame from a list of lists. The lists must have the
same length, and the elements of the lists must be of the same data type.

import pandas as pd
data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
df = pd.DataFrame(data)
print(df)
# 0 1 2
0 1 2 3
1 4 5 6
2 7 8 9
11.Explain any five operations on Dataframe with example.
Selecting columns : You can select columns from a DataFrame using the loc or iloc accessors.
The loc accessor selects columns by name, and the iloc accessor selects columns by index.

import pandas as pd
df = pd.DataFrame({'Name': ['John Doe', 'Jane Doe', 'John Smith'], 'Age': [30, 25,
40]})
df = df['Name']
print(df)
Output:

0 John Doe

1 Jane Doe

2 John Smith
Adding columns : You can add columns to a DataFrame using the assign method. The assign method
takes a dictionary as an argument, where the keys are the column names and the values are the
values of the columns.

import pandas as pd
df = pd.DataFrame({'Name': ['John Doe', 'Jane Doe', 'John Smith'], 'Age': [30, 25,
40]})
df = df.assign(Country='USA')
print(df)
Output:

Name Age Country


0 John Doe 30 USA

1 Jane Doe 25 USA

2 John Smith 40 USA

Deleting columns : You can delete columns from a DataFrame using the drop method.
The drop method takes a list of column names as an argument.

import pandas as pd
df = pd.DataFrame({'Name': ['John Doe', 'Jane Doe', 'John Smith'], 'Age': [30, 25,
40], 'Country': ['USA', 'Canada', 'UK']})
df = df.drop('Country', axis=1)
print(df)
Output:

Name Age

0 John Doe 30

1 Jane Doe 25
2 John Smith 40

Filtering rows : You can filter rows from a DataFrame using the loc or iloc accessors. The loc accessor
filters rows by label, and the iloc accessor filters rows by index.
import pandas as pd
df = pd.DataFrame({'Name': ['John Doe', 'Jane Doe', 'John Smith'], 'Age': [30, 25, 40], 'Country':
['USA', 'Canada', 'UK']})
df = df[df['Age'] > 30]
print(df)
Output:

Name Age
1 Jane Doe 25
2 John Smith 40

Sorting rows : You can sort rows in a DataFrame using the sort_values method.
The sort_values method takes a column name as an argument, and it sorts the rows in ascending
order by default. You can also specify ascending=False to sort the rows in descending order.

import pandas as pd
df = pd.DataFrame({'Name': ['John Doe', 'Jane Doe', 'John Smith'], 'Age': [30, 25, 40], 'Country':
['USA', 'Canada', 'UK']})
df = df.sort_values('Age')
print(df)
Output:

Name Age Country

1 Jane Doe 25 Canada

0 John Doe 30 USA

2 John Smith 40 UK

12.Explain Bar Graph creation using Matplot Library module


A bar chart or bar graph is a chart or graph that presents categorical data with rectangular bars
with heights or lengths proportional to the values that they represent. The bars can be plotted
vertically or horizontally.
1.Import the matplotlib.pyplot module.

2.Create a figure object.


3.Create a bar plot using the plt.bar() function. The plt.bar() function takes two arguments: the x-axis
values and the y-axis values.

4.Add a title to the plot using the plt.title() function.

5.Add labels to the x-axis and y-axis using the plt.xlabel() and plt.ylabel() functions.

6.Show the plot using the plt.show() function.

Syntax: ax.bar(x, height, width, bottom, align)

Here is an example of how to create a bar graph using the Matplotlib library module:
import matplotlib.pyplot as plt

country = ['A', 'B', 'C', 'D', 'E']

gdp_per_capita = [45000, 42000, 52000, 49000, 47000]


plt.bar(country, gdp_per_capita)
plt.title('Country Vs GDP Per Capita')

plt.xlabel('Country')

plt.ylabel('GDP Per Capita')

plt.show()

###This code will create a bar graph with three bars. The first bar will have a height of 10, the second
bar will have a height of 20, and the third bar will have a height of 30. The x-axis will be labeled "X-
Axis" and the y-axis will be labeled "Y-Axis". The title of the plot will be "Bar Graph".
13.Write a program to display histogram

To create a histogram the first step is to create bin of the ranges, then distribute the whole range of
the values into a series of intervals, and count the values which fall into each of the intervals.Bins are
clearly identified as consecutive, non-overlapping intervals of variables.The matplotlib.pyplot.hist()
function is used to compute and create histogram of x.

from matplotlib import pyplot as plt


import numpy as np
# Creating dataset
a = np.array([22, 87, 5, 43, 56,
73, 55, 54, 11,
20, 51, 5, 79, 31,
27])
fig, ax = plt.subplots(figsize =(10, 7))
ax.hist(a, bins = [0, 25, 50, 75, 100])

plt.show()
14.Write a Python program to display Pie Chart showing percentage of employees in each
department. Assume there are 4 departments namely Sales , Production , HR and Finance.

import matplotlib.pyplot as plt


# Department names and corresponding employee counts
departments = ['Sales', 'Production', 'HR', 'Finance']
employee_counts = [25, 30, 15, 20]
# Creating the pie chart
plt.pie(employee_counts, labels=departments, autopct='%1.1f%%')

# Adding a title
plt.title('Employee Distribution by Department')
# Displaying the pie chart
plt.show()

15.Write a Python Program to create Line Graph showing number of students of a college in
various Years. Consider 8 years data
import matplotlib.pyplot as plt
# Years and corresponding number of students
years = [2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022]
student_counts = [500, 600, 700, 800, 900, 1000, 1100, 1200]
# Creating the line graph
plt.plot(years, student_counts)
# Adding labels and title
plt.xlabel('Years')
plt.ylabel('Number of Students')
plt.title('Number of Students in College over the Years')
# Displaying the line graph
plt.show()

You might also like