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

Data Analysis Using Python - Study Material

Uploaded by

Eshita Das
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 views20 pages

Data Analysis Using Python - Study Material

Uploaded by

Eshita Das
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

OPERATORS

 Arithmetic Operator
a=7
b=2
print(a+b) ## addition
print(a*b) ## multiplication
print(a/b) ## division
print(a%b) ## modulo operation
print(a//b) ## floor division
print(a**b) ## exponential

 Comparison Operator
x=5
y=5
print(x==y) #o/p True
print(x!=y) #o/p False
print(x>y) #o/p False
print(x>=y) #o/p True
print(x<=y) #o/p True

 Logical Operator
x=['6','7']
y=['6','7','8']
print(x and y) #o/p ['6','7','8']
print(x or y) #o/p ['6','7']
print(not x) # o/p False
[Note: Python considers empty strings as having a Boolean value “False” and non empty
strings as having a Boolean value “True”.
For the ‘and’ operator if the left value is true, then the right value is checked and returned. If
the left value is false then it is returned.
For the ‘or’ operator if the left value is true, then it is returned, otherwise if the left value is
false, then the right value is returned.]
 Membership Operator
x=["hello","hi",'Bye']
print('hello' not in x) #o/p False
print('hello' in x) #o/p True

LIST
 Create & Print a list
x = [3, 1, 2]
print(x) # Prints [3, 1, 2]

 Add different types of element within LIST


x = [3, 1, 2]
x[2] = 'foo'
print(x) # Prints "[3, 1, 'foo']"

 List Slicing
mylist=['mouse','keyboard', 'monitor','printer','scanner','usb']
print(mylist[0:5]) #o/p ['mouse', 'keyboard', 'monitor', 'printer', 'scanner']
print(mylist[-3:]) #o/p ['printer', 'scanner', 'usb']
print(mylist[-1]) #o/p usb
print(mylist[-5:-1]) #o/p ['keyboard', 'monitor', 'printer', 'scanner']

 Change Element
mylist=['mouse','keyboard', 'monitor','printer','scanner','usb']
mylist[2]='CPU'
print(mylist) #o/p ['mouse', 'keyboard', 'CPU', 'printer', 'scanner', 'usb']

 Append element at the LAST POSITION of the list


[Link]('hello')
print(mylist) #o/p ['mouse', 'keyboard', 'CPU', 'printer', 'scanner', 'usb', 'hello']

 Append element at ANY POSITION in the list


[Link](2,'hi')
print(mylist) # o/p ['mouse', 'keyboard', 'hi', 'CPU', 'printer', 'scanner', 'usb', 'hello']
 Remove element at any position from the list
[Link]('hi')
print(mylist) #o/p ['mouse', 'keyboard', 'CPU', 'printer', 'scanner', 'usb', 'hello']

[Link](-2)
print(mylist) #o/p ['mouse', 'keyboard', 'CPU', 'printer', 'scanner', 'hello']

print([Link](-3)) # o/p printer

 Join two lists


mylist1=['mouse','keyboard', 'monitor','printer','scanner','usb',1]
mylist2 = [1,2,3]
mylist=mylist1+mylist2
print(mylist) # o/p prints ['mouse','keyboard', 'monitor','printer','scanner','usb',1,1,2,3]

 Sort a list
Ex 1:
numbers = [4, 2, 9, 1, 5, 6]
[Link]() # ascending
print(numbers) # o/p [1, 2, 4, 5, 6, 9]

Ex 2:
a = ["saw", "small", "he", "foxes", "six"]
[Link](key = len)
print(a) # o/p ['he', 'saw', 'six', 'small', 'foxes']

### for descending


numbers = [4, 2, 9, 1, 5, 6]
n= [Link](reverse=True) # descending
print(numbers) # o/p [9, 6, 5, 4, 2, 1]

 LIST COMPREHENSION :

1. EXAMPLE 1
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
new = [x for x in fruits if "a" in x]
newlist = [x if "a" in x else 0 for x in fruits]
print(“new = ”,new , “newlist = ”, newlist)
# o/p
new = ['apple', 'banana', 'mango'] newlist = ['apple', 'banana', 0, 0, 'mango']
2. EXAMPLE 2
nums = [0, 1, 2, 3, 4]
even_squares = [x ** 2 for x in nums if x % 2 == 0]
print(even_squares) # Prints "[0, 4, 16]"

DICTIONARIES
 Create Dictionary
mydict={'Name':'Ram','Age':22,'address':'Kolkata'}
print(mydict) # o/p {'Name': 'Ram', 'Age': 22, 'address': 'Kolkata'}

 Search value from Dictionary


print([Link]('address')) #o/p Kolkata

 Change value in Dictionary using Key


mydict['Age']=30
print(mydict) #o/p {'Name': 'Ram', 'Age': 30, 'address': 'Kolkata'}

 Add value in Dictionary using Key


mydict['Salary']=2000
print(mydict) # o/p {'Name': 'Ram', 'Age': 30, 'address': 'Kolkata', 'Salary': 2000}

 Remove value in Dictionary using Key


[Link]('Age')
print(mydict) # o/p {'Name': 'Ram', 'address': 'Kolkata', 'Salary': 2000}

 Sorting of Dictionary

 Sorting by Keys: You can sort a dictionary by its keys using the sorted() function.

my_dict = {'banana': 3, 'apple': 5, 'cherry': 2}


sorted1 = dict(sorted(my_dict.items()))
print(sorted1)

#o/p:
{'apple': 5, 'banana': 3, 'cherry': 2}

 Sorting by Values: To sort by values, use a lambda function as the key in sorted().

sorted2 = dict(sorted(my_dict.items(), key=lambda item: item[1]))


print(sorted2)
#o/p:
{'cherry': 2, 'banana': 3, 'apple': 5}

 Reverse Sorting: You can reverse the sorting order by adding the reverse=True
argument.

sorted3 = dict(sorted(my_dict.items(), reverse=True))


sorted4 = dict(sorted(my_dict.items(), key=lambda item: item[1], reverse=True))

 DICTIONARY COMPREHENSION :

1. EXAMPLE-1
nums = [0, 1, 2, 3, 4]
even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
print(even_num_to_square) # o/p {0: 0, 2: 4, 4: 16}

SETS
animals = {'cat', 'dog'}
print(animals) # o/p {'dog', 'cat'}
print('cat' in animals) # Check if an element is in a set; prints "True"
print('fish' in animals) # o/p "False"
[Link]('fish') # Add an element to a set
print(animals) # o/p {'dog', 'cat', 'fish'}
[Link]('cat') # Adding an element that is already in the set does nothing
[Link]('cat') # Remove an element from a set
print(animals) # o/p {'dog', 'fish'}
[#[Link]() removes arbitrary elements therefore doesn’t make sense]

 Set Operations
x={'a','b', 'c'}
y={1,2,'b',3}
z=[Link](y) #x ∪ y
t = [Link](y) #x ∩ y
u = [Link](y) #x∖y
v= [Link](x) #y∖x
w = x.symmetric_difference(y) # (x ∪ y) ∖ (x ∩ y) either but not both
print("z: ",z ,"t: ",t ,"u: ",u,"v: ",v, "w: ",w)
#o/p:
z: {1, 2, 'b', 3, 'c', 'a'} t: {'b'} u: {'c', 'a'} v: {1, 2, 3} w: {1, 2, 3, 'c', 'a'}
 Set comprehensions
from math import sqrt #in-built square root function
nums = {int(sqrt(x)) for x in range(30)}
print(nums)
# o/p {0, 1, 2, 3, 4, 5} ##values are not repeated because set
[NOTE: had it been nums = [int(sqrt(x)) for x in range(30)] output would have been [0, 1, 1,
1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5]]

 Removing duplicates from list


You can remove duplicate values from a list in Python by converting the list to a set (which
automatically removes duplicates) and then converting it back to a list.

Example:
my_list = [1, 3, 4, 2, 2, 4, 5, 6, 3, 6]
new_list = list(set(my_list))
print("List after removing duplicates:", new_list)

#o/p:
List after removing duplicates: [1, 2, 3, 4, 5, 6]

PROBLEM: (involving set, dictionary, list)


Given two sets English = {'Tay', 'Sam', 'John', 'Delilah', 'Hugh', 'Josh'} and French = {'Mark',
'Josh', 'Pam', 'Tay', 'Rose'}, write a python code to
i. Find and print the names of students who are enrolled in both languages.
ii. Find and print the names of students who are enrolled in either English or French,
but not both.
iii. Create a dictionary where keys are student names and values are lists of the
languages they are enrolled in.

Sol:
English = {'Tay', 'Sam', 'John', 'Delilah', 'Hugh', 'Josh'}
French = {'Mark', 'Josh', 'Pam', 'Tay', 'Rose'}
both_languages = [Link](French)
print("Students enrolled in both English and French:", both_languages)

either_but_not_both = English.symmetric_difference(French)
print("Students enrolled in either English or French, but not both:", either_but_not_both)

students = [Link](French)
enrollment_dict = {}

for x in students:
subjects = [ ]
if x in English:
[Link]("English")
if x in French:
[Link]("French")
enrollment_dict[x] = subjects

print("\nEnrollment dictionary:")
for x, y in enrollment_dict.items():
print(x, ":", y)

TUPLE
mytuple=('mouse','keyboard', 'monitor','printer','scanner','usb')
print(type(mytuple)) # o/p <class 'tuple'>

 Display any element of TUPLE


print(mytuple[2]) # o/p monitor

 Display range of element of TUPLE


print(mytuple[3:5]) # o/p ('printer', 'scanner')

 Change any element of TUPLE


mylist=list(mytuple) # convert to list as tuple object does not support item assignment
mylist[1]='cpu' # change in list
mytuple=tuple(mylist) # convert back to tuple
print(mytuple) # o/p ('mouse', 'cpu', 'monitor', 'printer', 'scanner', 'usb')

 Join two tuples


mytuple1=('mouse','keyboard', 'monitor','printer','scanner','usb')
mytuple2 = (1,2,3)
mytuple=mytuple1+mytuple2
print(mytuple) # o/p ('mouse', 'keyboard', 'monitor', 'printer', 'scanner', 'usb', 1, 2, 3)

For LOOP
Example 1:
mylist=['MOUSE','CPU','PRINTER']
for x in mylist:
print(x)

Example 2:
for x in range(20):
print(x)
Example 3:
for x in range(2,10):
print(x) # prints 2,3,4,…,9

 Range Increasing/Decreasing
for x in range(10,1,-2):
print(x) #prints 10,8,6,4,2

LIBRARY – NUMPY
 Program 1d Array Using Numpy
import numpy as np
a = [Link]([1, 2, 3]) # Create a rank 1 array
print(type(a)) # o/p <class '[Link]'>
print([Link]) # o/p (3,)

 Program 2d Array Using Numpy


import numpy as np
n=[Link]([[1,2,3,4,5],[10,11,12,13,14]])
print(n) # o/p [[ 1 2 3 4 5]
[10 11 12 13 14]]
st nd
print(n[0,1]) # o/p 2 #1 row, 2 col
print(n[1,1]) #o/p 11

 Program 3d Array Using Numpy


import numpy as np
n=[Link]([[[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]]])
print(n) # o/p [[[1 2 3]
[4 5 6]]

[[1 3 5]
[9 5 7]]]
print(n[0,1,2]) #(sheet, row, col) #1st sheet 2nd row 3rd col o/p 6

 Program For Sorting Number In 1d Array Using Numpy


import numpy as np
n=[Link]([10,9,0,100,-5])
print([Link](n)) # o/p [ -5 0 9 10 100]
 Program For Sorting String/ Text In 1d Array Using Numpy
import numpy as np
n=[Link](["Delhi","Zambia","Jaipur","Agartala","Anadaman"])
print([Link](n)) #o/p ['Agartala' 'Anadaman' 'Delhi' 'Jaipur' 'Zambia'] #Alphabetic order

 Program For building some specific Matrix using Numpy


Ex 1:
import numpy as np
a = [Link]((3,2),int) #datatype # o/p [[0 0]
[0 0]
[0 0]]

Ex 2:
import numpy as np
c = [Link]((2,2), 7) # Create a constant array
print(c) # o/p [[7 7]
[7 7]]

Ex 3:
import numpy as np
d = [Link](2) # Create a 2x2 identity matrix
print(d) # Prints "[[ 1. 0.]
# [ 0. 1.]]"

Ex 4: Create a 3x3 matrix with random integers from 1 to 9.


import numpy as np
mat = [Link](1, 10, size=(3, 3))
print(mat) # Might print [[7 1 6]
[2 7 2]
[5 3 7]]

 Calculating sum of diagonal elements (Trace) and Determinant of a


Matrix
import numpy as np
mat = [Link](1, 10, size=(3, 3))
diagonal_sum = [Link](mat) # Calculate the sum of the diagonal elements
determinant = [Link](mat) # Calculate the determinant of the matrix
print("Matrix:")
print(mat)
print("Sum of diagonal elements:", diagonal_sum)
print("Determinant of the matrix:", determinant)
 Application Of Numpy On Array/Matrix (Array Math)
Array math: Basic mathematical functions operate element-wise on arrays, and are available
both as operator overloads and as functions in the numpy module:

 Sum
import numpy as np
x = [Link]([[1,2],[3,4]], dtype=np.float64)
y = [Link]([[5,6],[7,8]], dtype=np.float64)
print(x + y)
print([Link](x, y))
# both produce the array [[ 6.0 8.0]
[10.0 12.0]]

 Product (Element wise)


print(x * y)
print([Link](x, y)) ;
#both produce the array
[[ 5.0 12.0]
[21.0 32.0]]

 Matrix multiplication
import numpy as np
x = [Link]([[1,2],[3,4]])
y = [Link]([[5,6],[7,8]])
print([Link](y))
print([Link](x,y))
# both produce the rank 2 array
[[19 22]
[43 50]]

 Transposing a matrix;
To transpose a matrix, simply use the T attribute of an array object:
import numpy as np
x = [Link]([[1,2], [3,4]])
print(x) # o/p [[1 2]
[3 4]]
print(x.T) # o/p "[[1 3]
[2 4]]"
[Note that taking the transpose of a rank 1 array does nothing:
v = [Link]([1,2,3])
print(v) # o/p [1 2 3]
print(v.T) # o/p [1 2 3]]

 Application Of Numpy On Array/Matrix (Array Math)


Numpy provides many useful functions for performing computations on arrays; one of the
most useful is sum:
 for 2D array
import numpy as np
x = [Link]([[1,2],[3,4]])
print([Link](x)) # Compute sum of all elements; o/p 10
print([Link](x, axis=0)) # Compute sum of two rows; o/p [4 6]
print([Link](x, axis=1)) # Compute sum of two columns; o/p [3 7]

 Solving system of linear equations


Example:
Solve the following system of equations
4𝑥 + 2𝑦 − 𝑧 = 8
𝑥 − 5𝑦 + 3𝑧 = −3
2𝑥 + 𝑦 + 4𝑧 = 10

import numpy as np
A = [Link]([[4, 2, -1], [1, -5, 3], [2, 1, 4]]) # Coefficient matrix (A)
B = [Link]([8, -3, 10]) # Constants on the right-hand side (B)
solution = [Link](A, B)
print("Solution for x, y, z:")
print(solution)

Basics of Data Handling and Analysis Using Python


Data handling is an essential part of data analysis and involves various tasks like importing,
cleaning, sorting, filtering, summarizing data, and dealing with missing values. Additionally,
calculating key statistics such as measures of central tendency (mean, median, mode) and the
standard deviation is fundamental to understanding the dataset. Python, with libraries like
Pandas, NumPy, provides a powerful set of tools for these tasks.

A Series is a one-dimensional array-like object containing a sequence of values of the same


type and an associated array of data labels, called its index.
 Calculating Central tendency of a Series
import pandas as pd
mylist = [2,4,5,9,3,3,8]
s = [Link](mylist)
print(s)
print([Link]())
print([Link]())
print([Link]())
#o/p
0 2
1 4
2 5
3 9
4 3
5 3
6 8
dtype: int64
4.857142857142857
4.0
2.6726124191242437

print([Link]()[0]) # mode() returns a Series. If there are multiple modes, you


can access them as mode[0], mode[1], etc.
#o/p
3

 Importing Data
The first step in handling data is importing it into Python. This is typically done using the
Pandas library, which supports reading data from various file formats like CSV, Excel, SQL
databases, etc.

A DataFrame represents a rectangular table of data and contains an ordered, named collection
of columns, each of which can be a different value type (Numeric, string, Boolean etc.). It has
both a row and column index. There are many ways to construct a DataFrame, though one of
the most common is from a dictionary of equal-length lists.

Example 1:

import pandas as pd
data = {“state”: [“Ohio”, “Ohio”, “Ohio”, “Nevada”, “Nevada”, “Nevada”], “year”: [2000,
2001,2002,2001,2002,2003], “pop” : [1.5,1.7,3.6,2.4,2.9,3.2]}
df = [Link](data)

#o/p
state year pop
0 Ohio 2000 1.5
1 Ohio 2001 1.7
2 Ohio 2002 3.6
3 Nevada 2001 2.4
4 Nevada 2002 2.9
5 Nevada 2003 3.2

Importing a CSV file ([Link]) into a DataFrame

import pandas as pd
df = pd.read_csv(r'C:\Users\USER\Desktop\[Link]') #specify the file location
# df = pd.read_csv('[Link]') #if in the same directory

 Cleaning Data
Data cleaning is crucial to remove or handle incomplete, inaccurate, or irrelevant data.
Handling Missing Data: Missing values can be handled by either a) removing them or b)
assigning them (replacing with a calculated value).

a) Remove rows with missing values

import numpy as np
import pandas as pd
data = [Link]([[1., 6.5, 3.],[1., [Link], [Link]],[[Link], [Link], [Link]],[[Link],
6.5,3.]])
print([Link]().sum()) # Displays the count of missing values in each column
data_cleaned1 = [Link]()
print(data_cleaned1)
#o/p
0 1 2
0 1.0 6.5 3.0

[drops any row containing a missing value and returns new object and do not modify the
contents of the original object]

b) Remove columns with missing values


import numpy as np
import pandas as pd
data = [Link]([[1., 6.5, 3.],[1., [Link], [Link]],[2, [Link], [Link]],[9, 6.5,3.]])
data_cleaned2 = [Link](axis = 'columns')
print(data_cleaned2)
#o/p
0
0 1.0
1 1.0
2 2.0
3 9.0
c) Remove rows with missing values only in specific columns
import numpy as np
import pandas as pd
data = [Link]([[1., 6.5, 3.],[1., [Link], 5.],[2, 7, [Link]],[9, 6.5,3.]])
data_cleaned3 = [Link](subset=[1]) #if you want to remove rows with NaN in
2nd col
print(data_cleaned3)

#o/p
0 1 2
0 1.0 6.5 3.0
2 2.0 7.0 NaN
3 9.0 6.5 3.0

d) Fill missing values with the mean of the column


# data['column_name'] = data['column_name'].fillna(data['column_name'].mean())

import numpy as np
import pandas as pd
data = [Link]([[1., 6.5, 3.],[1., [Link], 5.],[2, 7, [Link]],[9, 6.5,3.]])
data[1] = data[1].fillna(data[1].mean())
print(data)
#o/p
0 1 2
0 1.0 6.500000 3.0
1 1.0 6.666667 5.0
2 2.0 7.000000 NaN
3 9.0 6.500000 3.0

e) Fill missing values with the median of the column


data['column_name'] = data['column_name'].fillna(data['column_name'].median())

 Sorting Data
Sorting helps organize the data based on specific columns for easier analysis or presentation.

Example: Sorting by the "Salary" column in ascending and descending order.

import pandas as pd
data = {"Name": ['Ron', 'Josh', 'Hannah','Joy', 'Tim', 'Audrey'], 'Age': [25, 27,21, 28,20,27],
'Salary' : [1.5,2.3,1.2,1.8,1.7,2.9]}
df = [Link](data)
print(df.sort_values("Salary") #ascending
print(df.sort_values("Salary", ascending = False)) #descending
 Filtering Data
Filtering is used to extract relevant subsets of data based on specific conditions. This helps in
focusing on particular rows that meet the criteria for analysis.

Example: Filter rows where the salary is greater than 1.5.

Sol:
filtered_data = data[data['Salary'] > 1.5]

PROBLEM: You are provided with a dataset called "student_data.csv" containing the
following columns: “Name”, “Age” (some values may be missing or incorrect, i.e., negative
or zero), “height”. Write a Python program to:
i. Replace the missing values in the “Age” column with the median age of the dataset.
ii. Remove all rows where the value in the “Age” column is less than or equal to zero.
iii. Filter the dataset to include only rows where “height” is greater than 155.

Sol:

import pandas as pd
data = pd.read_csv(r'C:\Users\USER\Desktop\student_data.csv')
data['Age'] = data['Age'].fillna(data['Age'].median())
data = data[data["Age"]>0] #filtering
data = data[data["height"]>155]
print(data)

 Calculating Central Tendency


Example:

import pandas as pd
data = {"Name": ['Ron', 'Josh', 'Hannah','Joy', 'Tim', 'Audrey'], 'Age': [25, 27,21, 28,20,27],
'Salary' : [1.5,2.3,1.2,1.8,1.7,2.9]}
df = [Link](data)
print("mean value = ",df['Age'].mean())
print("median value = ",df['Age'].median())
print("mode value = ",df['Age'].mode()[0])
print("standard deviation = ",df['Age'].std())

#o/p:
mean value = 24.666666666666668
median value = 26.0
mode value = 27
standard deviation = 3.3862466931200785
 Summarizing Data
Summarizing helps generate insights by calculating summary statistics such as the mean,
median, count, and more for the dataset.

Example: Get a summary of the entire dataset.

summary = [Link]()

This provides count, mean, standard deviation, min, max, and quartiles for numeric columns.

Example Workflow: Below is an example workflow that uses the steps mentioned above
import pandas as pd
data = pd.read_csv('employee_data.csv') # Import Data

data['Salary'] = data['Salary'].fillna(data['Salary'].mean()) # Clean Data (handle missing


values)
sorted_data = data.sort_values(by='Age') # Sort Data by Age

filtered_data = sorted_data[sorted_data['Salary'] > 50000] # Filter Data to only include


#rows where Salary is greater than 50,000
summary = filtered_data.describe() # Summarize Data

mean_salary = filtered_data['Salary'].mean() # Calculate Central Tendency


median_salary = filtered_data['Salary'].median()
mode_salary = filtered_data['Salary'].mode()[0]

std_dev_salary = filtered_data['Salary'].std() # Calculate Standard Deviation

print("Summary:\n", summary) # Display results


print(f"Mean Salary: {mean_salary}")
print(f"Median Salary: {median_salary}")
print(f"Mode Salary: {mode_salary}")
print(f"Standard Deviation of Salary: {std_dev_salary}")

Data Visualization using Python: Line Plots, Bar Plots, and


Histograms with Matplotlib
Matplotlib is a powerful plotting library in Python that allows for easy and flexible data
visualization. It is widely used for creating static, animated, and interactive plots. Below is an
overview of some of the basic plot types, including line plots, bar plots, and histograms, with
examples of how to use them in Python.
Line Plots

A line plot is useful for visualizing data that changes over time or to depict the trend of a
dataset. It connects individual data points with a continuous line, making it easier to see
patterns or trends.

Example Code for Line Plot:

import [Link] as plt


months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
sales_a = [1500, 1200, 1300, 1400, 1600, 1700]
sales_b = [1100, 1150, 1200, 1250, 1300, 1350]
[Link](months, sales_a, label='Product A Sales', marker='o')
[Link](months, sales_b, label='Product B Sales', marker='x')
[Link]('Months')
[Link]('Sales')
[Link]('Monthly Sales Data for Product A and B')
[Link]()
[Link]()

Key Points:

 Use [Link]() to create a line plot.


 Add markers to points using the marker parameter.
 Use [Link](), [Link](), and [Link]() for axis labels and titles.
 [Link]() displays labels for each line.
Bar Plots

Bar plots are used to compare different categories or groups. Each bar represents a category,
and the length of the bar corresponds to the value it represents.

Example Code for Bar Plot:

import [Link] as plt


categories = ['Product A', 'Product B', 'Product C']
values = [400, 500, 300]
[Link](categories, values, color=['blue', 'green', 'red'])
[Link]('Products')
[Link]('Sales')
[Link]('Sales of Products')
[Link]()

Key Points:

 Use [Link]() to create a vertical bar plot.


 Categories are placed on the x-axis, and the height of bars represents the values.
 You can customize the color of the bars with the color parameter.

Problem 1: Given a CSV file named "sales_data.csv" containing columns "Month", "Product
A Sales", and "Product B Sales". Write a Python script that:
i. Imports the data using Pandas.
ii. Creates a bar plot comparing the total sales of Product A and Product B. Label
the axes and provide a title.
Sol:

import pandas as pd
import [Link] as plt
data = pd.read_csv(r'C:\Users\USER\Desktop\sales_data.csv')
categories = ["Product A", "Product B"]
values = [data["Product A Sales"].sum(), data["Product B Sales"].sum()]
[Link](categories, values, color=['blue', 'green'])
[Link]('Products')
[Link]('Sales')
[Link]('Sales of Products')
[Link]()

o/p

Histograms

Histograms are used to represent the distribution of numerical data. It divides the data into
bins (intervals) and shows how many data points fall within each bin.

Example Code for Histogram:

import [Link] as plt


ages = [21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 35, 40, 45, 50, 55, 60]
[Link](ages, bins=4, color='lightgreen', edgecolor='black')
[Link]('Age')
[Link]('Frequency')
[Link]('Age Distribution')
[Link]()
Key Points:

 Use [Link]() to create a histogram.


 The bins parameter controls the number of intervals.

Summary:

 Line Plots: Best for showing trends and continuous data.


 Bar Plots: Ideal for comparing categorical data or different groups.
 Histograms: Useful for visualizing the distribution of data.

Matplotlib provides great flexibility to customize these plots, such as adding labels, legends,
colors, and grids, to create informative visualizations that suit different kinds of data.

Reference:
Wes Mckinney, “Python for Data Analysis: Data Wrangling with Pandas, NumPy, and
IPython”, 2nd Edition (2017), United States: O'Reilly Media.

You might also like