3.
Write a python program to calculate sum, mean, median, mode, Standard deviation of
following values:
CA:[87,89,98,94,78,77]
import statistics
import math
CA = [87, 89, 98, 94, 78, 77]
# Sum
total = sum(CA)
# Mean
mean = total / len(CA)
# Median
median = [Link](CA)
# Mode (handle no-mode case)
try:
mode = [Link](CA)
except [Link]:
mode = "No mode"
# Standard Deviation (Population)
std_dev = [Link](sum((x - mean) ** 2 for x in CA) / len(CA))
print("Values:", CA)
print("Sum =", total)
print("Mean =", mean)
print("Median =", median)
print("Mode =", mode)
print("Standard Deviation =", std_dev)
[Link] a python program to fill missing values (NaN) in a DataFrame using fillna() with
mean value and detect duplicates using duplicated() method.
import pandas as pd
import numpy as np
# Create DataFrame with missing values and duplicates
data = {
'Marks': [85, 90, [Link], 88, 90, [Link]],
'Age': [20, 21, 22, [Link], 21, 22]
}
df = [Link](data)
print("Original DataFrame:")
print(df)
# Fill NaN values with mean
df_filled = [Link]([Link]())
print("\nDataFrame after filling NaN values with mean:")
print(df_filled)
# Detect duplicate rows
duplicates = df_filled.duplicated()
print("\nDuplicate rows (True indicates duplicate):")
print(duplicates)
5 Create a DataFrame from a dictionary and display the first 5 rows.
import pandas as pd
# Create dictionary
data = {
'Name': ['Amit', 'Neha', 'Rahul', 'Pooja', 'Sanjay', 'Kiran'],
'Age': [21, 22, 20, 23, 24, 22],
'Marks': [78, 85, 88, 90, 76, 82]
}
# Create DataFrame
df = [Link](data)
# Display first 5 rows
print("First 5 rows of DataFrame:")
print([Link]())
6Load [Link] file into a DataFrame
a) check its shape
b) Add a new column total_amount = price * quantity.
c) Select only the columns: customer_name, product, quantity, price.
d) Filter rows where the region is "North".
import pandas as pd
# Load CSV file into DataFrame
df = pd.read_csv("[Link]")
# a) Check shape of DataFrame
print("Shape of DataFrame:", [Link])
# b) Add new column: total_amount = price * quantity
df['total_amount'] = df['price'] * df['quantity']
print("\nDataFrame after adding total_amount column:")
print([Link]())
# c) Select specific columns
selected_columns = df[['customer_name', 'product', 'quantity', 'price']]
print("\nSelected Columns:")
print(selected_columns.head())
# d) Filter rows where region is 'North'
north_region = df[df['region'] == 'North']
print("\nRows where region is North:")
print(north_region)
Set B
Consider a following record in DataFrame IPL.
Player Team Category BidPrice Runs
Hardik Pandya Mumbai Indians Batsman 13 1000
K L Rahul Kings Eleven Batsman 12 2400
Andre Russel Kolkata Knight Riders Batsman 7 900
Jasprit Bumrah Mumbai Indians Bowler 10 200
Virat Kohli RCB Batsman 17 3600
Rohit Sharma Mumbai Indians Batsman 15 3700
Create a above DataFrame in python write python code for following
a) Retrieve first 2 rows
b) Retrieve last 3 rows
c) Add null values in DataFrame.
d) Find most expensive player.
e) Print total players per team.
f) Find average runs of each player.
g) Drop rows with missing data.
import pandas as pd
import numpy as np
# Create DataFrame
data = {
'Player': ['Hardik Pandya', 'K L Rahul', 'Andre Russel',
'Jasprit Bumrah', 'Virat Kohli', 'Rohit Sharma'],
'Team': ['Mumbai Indians', 'Kings Eleven', 'Kolkata Knight Riders',
'Mumbai Indians', 'RCB', 'Mumbai Indians'],
'Category': ['Batsman', 'Batsman', 'Batsman',
'Bowler', 'Batsman', 'Batsman'],
'BidPrice': [13, 12, 7, 10, 17, 15],
'Runs': [1000, 2400, 900, 200, 3600, 3700]
}
IPL = [Link](data)
print("IPL DataFrame:")
print(IPL)
a)Retrieve first 2 rows
print("\nFirst 2 rows:") print([Link](2))
b)Retrieve last 3 rows
print("\nLast 3 rows:") print([Link](3))
c)Add null values in DataFrame
[Link][2, 'Runs'] = [Link]
[Link][4, 'BidPrice'] = [Link]
print("\nDataFrame after adding NULL values:")
print(IPL)
d)Find most expensive player
most_expensive = [Link][IPL['BidPrice'].idxmax()] print("\nMost
expensive player:") print(most_expensive)
e)Print total players per team
print("\nTotal players per team:") print(IPL['Team'].value_counts())
f)Find average runs
avg_runs = IPL['Runs'].mean() print("\nAverage runs of players:",
avg_runs)
g)Drop rows with missing data
IPL_cleaned = [Link]() print("\nDataFrame after dropping rows
with missing data:") print(IPL_cleaned)
Create a following DataFrame named as “data”. Write the python code
for the following
commands.
Company Count Price
Pencil Apsara 15 250
Pencil Natraj 20 200
Pen Cello 25 600
Pen Parkar 35 900
Eraser Apsara 20 300
a) Find all rows with the label “Pencil”. Extract all columns
b) Change the Eraser count as 25 instead of 20.
c) List only the columns Company and Price.
d) List only rows with labels ‘Pencil’ and ‘Pen’
e) Delete column Count from the above DataFrame.
import pandas as pd
# Create DataFrame
data = [Link]({
'Company': ['Apsara', 'Natraj', 'Cello', 'Parkar', 'Apsara'],
'Count': [15, 20, 25, 35, 20],
'Price': [250, 200, 600, 900, 300]
}, index=['Pencil', 'Pencil', 'Pen', 'Pen', 'Eraser'])
print("Original DataFrame:")
print(data)
a) Find all rows with label “Pencil” and extract all
columns
print("\nRows with label 'Pencil':")
print([Link]['Pencil'])
b) Change Eraser count from 20 to 25
[Link]['Eraser', 'Count'] = 25
print("\nDataFrame after updating Eraser count:")
print(data)
c) List only columns Company and Price
print("\nCompany and Price columns:")
print(data[['Company', 'Price']])
d) List only rows with labels ‘Pencil’ and ‘Pen’
print("\nRows with labels Pencil and Pen:")
print([Link][['Pencil', 'Pen']])
e) Delete column Count
data = [Link](columns=['Count']) print("\nDataFrame after deleting
Count column:") print(data)
Write a python program to join the two DataFrames with matching
records from both
sides where available.
student_data1: Student_data2:
Id Name Marks Id Name Marks
0 S2 Ryder Storey 210 0 S4 Scarlette Fisher 201
1 S3 Bryce Jensen 190 1 S5 Carla Williamson 200
2 S4 Ed Bernal 222 2 S6 Dante Morse 198
3 S5 Kwame Morin 199 3 S7 Kaiser William 219
4 S5 Kwame Morin 199 4 S8 Madeeha Preston 201
import pandas as pd
# Create first DataFrame
student_data1 = [Link]({
'Id': ['S2', 'S3', 'S4', 'S5', 'S5'],
'Name': ['Ryder Storey', 'Bryce Jensen', 'Ed Bernal',
'Kwame Morin', 'Kwame Morin'],
'Marks': [210, 190, 222, 199, 199]
})
# Create second DataFrame
student_data2 = [Link]({
'Id': ['S4', 'S5', 'S6', 'S7', 'S8'],
'Name': ['Scarlette Fisher', 'Carla Williamson', 'Dante Morse',
'Kaiser William', 'Madeeha Preston'],
'Marks': [201, 200, 198, 219, 201]
})
print("Student Data 1:")
print(student_data1)
print("\nStudent Data 2:")
print(student_data2)
# Inner join on Id
result = [Link](student_data1, student_data2, on='Id', how='inner')
print("\nJoined DataFrame (Matching records from both sides):")
print(result)