Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
23 views

Python Lab Practicles

Uploaded by

netflixbasic500
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Python Lab Practicles

Uploaded by

netflixbasic500
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 73

LAB PROGRAMS

Prof. Kuljeet Singh


UNIT 1
BASIC DATA TYPES AND CONTROL STRUCTURES
Program 1
Write a Python program to do arithmetical operations addition and subtraction.

# Addition
num1 = float(input("Enter the first number for addition: "))
num2 = float(input("Enter the second number for addition: "))
sum_result = num1 + num2
print(f"sum: {num1} + {num2} = {sum_result}")

Output:
Enter the first number for addition: 5
Enter the second number for addition: 6
sum: 5.0 + 6.0 = 11.0
Program 2
Write a Python program to find the area of a triangle.

# Input the base and height from the user


base = float(input("Enter the length of the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
# Calculate the area of the triangle
area = 0.5 * base * height
# Display the result
print(f"The area of the triangle is: {area}")

Enter the length of the base of the triangle: 10


Enter the height of the triangle: 15
The area of the triangle is: 75.0
Program 3
Write a Python program to do arithmetic operation division using ‘if else’ condition

# Division
num3 = float(input("Enter the dividend for division: "))
num4 = float(input("Enter the divisor for division: "))
if num4 == 0:
print("Error: Division by zero is not allowed.")
else:
div_result = num3 / num4
print(f"Division: {num3} / {num4} = {div_result}")

Enter the dividend for division: 25


Enter the divisor for division: 5
Division: 25.0 / 5.0 = 5.0
Program 4
Write a Python program to swap two variables.

# Input two variables


a = input("Enter the value of the first variable (a): ")
b = input("Enter the value of the second variable (b): ")
# Display the original values
print(f"Original values: a = {a}, b = {b}")
# Swap the values using a temporary variable
temp = a
a=b
b = temp
# Display the swapped values
print(f"Swapped values: a = {a}, b = {b}") Enter the value of the first variable (a): 5
Enter the value of the second variable (b):
9
Original values: a = 5, b = 9
Program 5
Write a Python program to generate a random number.

import random
print(f"Random number: {random.randint(1, 100)}")

Random number: 89
Program 6
Write a Python program to convert kilometers to meters.

kilometers = float(input("Enter distance in kilometers: "))


# Conversion factor: 1 kilometer = 1000 meters
conversion_factor = 1000
meters = kilometers * conversion_factor
print(f"{kilometers} kilometers is equal to {meters} meters")

Enter distance in kilometers: 5


5.0 kilometers is equal to 5000 meters
Program 7
Write a Python program to display calendar.

import calendar
year = int(input("Enter year: "))
month = int(input("Enter month: "))
cal = calendar.month(year, month)
print(cal)

Enter year: 2024


Enter month: 8
August 2024
Mo Tu We Th Fr Sa Su
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Program 8
Write a Python program to swap two variables without temp variable.
a=5
b = 10
# Swapping without a temporary variable
a, b = b, a
print("After swapping:")
print("a =", a)
print("b =", b)

After swapping:
a = 10
b=5
Program 9
Write a Python Program to Check if a Number is Positive, Negative or Zero.

num = float(input("Enter a number: "))


if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Enter a number: 9
Positive number
Program 10
Write a Python Program to Check if a Number is Odd or Even.

num = int(input("Enter a number: "))


if num%2 == 0:
print("This is a even number")
else:
print("This is a odd number")

Enter a number: 7
This is a odd number
Program 11
Check if a number is positive, negative, or zero

num = float(input("Enter a number: "))

if num > 0:
print(f"{num} is a positive number.")
elif num < 0:
print(f"{num} is a negative number.")
else:
print("The number is zero.")
Program 12
Sum of elements in a list

numbers = [1, 2, 3, 4, 5]
total = 0

for number in numbers:


total += number

print(f"The sum of the list elements is {total}.")


Program 13
Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How many terms? "))

# first two terms


n1, n2 = 0, 1
count = 0 # generate fibonacci sequence
else:
# check if the number of terms is valid print("Fibonacci sequence:")
if nterms <= 0: while count < nterms:
print("Please enter a positive integer") print(n1)
# if there is only one term, return n1 nth = n1 + n2
elif nterms == 1: # update values
print("Fibonacci sequence n1 = n2
upto",nterms,":") n2 = nth
print(n1) count += 1
Program 14

Print numbers from 1 to 10

i=1

while i <= 10:


print(i)
i += 1
Program 15
Find the factorial of a number

num = int(input("Enter a number: "))


factorial = 1
i=1

while i <= num:


factorial *= i
i += 1

print(f"The factorial of {num} is


{factorial}.")
Program 16
Find the first number in a list that is divisible by 5

numbers = [3, 8, 6, 10, 14, 5, 20]

for number in numbers:


if number % 5 == 0:
print(f"The first number divisible by 5 is {number}.")
break
Program 17
Print odd numbers only

# Program to print odd numbers in a range


for i in range(1, 20):
if i % 2 == 0:
continue
print(i)
UNIT 2
LISTS AND TUPLES
Program 1
Implementing Lists in Python Programs

1. Program to Sum Elements in a List

numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(f"Sum of list: {total}")

def sum_of_list(lst):
total = sum(lst)
return total

numbers = [1, 2, 3, 4, 5]
print(f"Sum of list: {sum_of_list(numbers)}")
Program 2
2. Program to Find the Maximum and Minimum in a List

numbers = [10, 20, 5, 30, 15]


max_num = max(numbers)
min_num = min(numbers)
print(f"Maximum: {max_num}, Minimum: {min_num}")

def find_max_min(lst):
return max(lst), min(lst)

numbers = [10, 20, 5, 30, 15]


max_num, min_num = find_max_min(numbers)
print(f"Maximum: {max_num}, Minimum: {min_num}")
Program 3
3. Program to Count Occurrences of Each Element

items = ['apple', 'banana', 'apple', 'orange', 'banana']


occurrences = {item: items.count(item) for item in set(items)}
print("Occurrences:", occurrences)

def count_occurrences(lst):
return {item: lst.count(item) for item in set(lst)}

items = ['apple', 'banana', 'apple', 'orange', 'banana']


occurrences = count_occurrences(items)
print("Occurrences:", occurrences)
Program 4
4. Program to Merge Two Lists

list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = list1 + list2
print(f"Merged list: {merged_list}")

def merge_lists(list1, list2):


return list1 + list2

list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = merge_lists(list1, list2)
print(f"Merged list: {merged_list}")
Program 5
5. Program to Remove Duplicates from a List

items = [1, 2, 2, 3, 4, 4, 5]
unique_items = list(set(items))
print(f"List without duplicates: {unique_items}")

def remove_duplicates(lst):
return list(set(lst))

items = [1, 2, 2, 3, 4, 4, 5]
unique_items = remove_duplicates(items)
print(f"List without duplicates: {unique_items}")
Program 6
6. Program to Generate a List of Squares

n=5
squares = [i**2 for i in range(n)] Output: List of squares: [0, 1, 4, 9, 16]
print(f"List of squares: {squares}")

def generate_squares(n):
return [i**2 for i in range(n)]

squares = generate_squares(5)
print(f"List of squares: {squares}")
Program 7
7. Accessing elements, slicing, and iterating through a tuple

# Defining a tuple
my_tuple = (10, 20, 30, 40, 50)

# Accessing elements using index


print(my_tuple[0]) # Output: 10
print(my_tuple[2]) # Output: 30

# Slicing a tuple (from index 1 to 3, exclusive)


print(my_tuple[1:4]) # Output: (20, 30, 40)

# Iterating through a tuple


for item in my_tuple:
print(item)
Program 8
8. WAP on basic operations like concatenation, repetition, and membership test.
# Concatenation of tuples
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
tuple3 = tuple1 + tuple2
print(f"Concatenated Tuple: {tuple3}") # Output: (1, 2, 3, 4, 5, 6)

# Repeating a tuple
repeated_tuple = tuple1 * 3
print(f"Repeated Tuple: {repeated_tuple}") # Output: (1, 2, 3, 1, 2, 3,
1, 2, 3)

# Checking if an element exists in a tuple (membership test)


print(2 in tuple1) # Output: True
print(7 in tuple1) # Output: False
Program 9
9. WAP to use tuple methods - count() and index()

# Tuple with duplicate elements


my_tuple = (1, 2, 3, 2, 4, 2, 5)

# count(): Returns the number of occurrences of an element


count_of_twos = my_tuple.count(2)
print(f"Count of 2 in tuple: {count_of_twos}") # Output: 3

# index(): Returns the first index of an element


index_of_three = my_tuple.index(3)
print(f"Index of 3 in tuple: {index_of_three}") # Output: 2
Program 10
10. WAP to use mixed tuples and nested tuples

# Tuple with mixed data types


mixed_tuple = (10, "Python", 3.14)
print(f"Mixed Tuple: {mixed_tuple}") # Output: (10, 'Python', 3.14)

# Nested tuple
nested_tuple = (1, (2, 3), (4, 5, 6))
print(f"Nested Tuple: {nested_tuple}") # Output: (1, (2, 3), (4, 5, 6))

# Accessing elements in a nested tuple


print(nested_tuple[1]) # Output: (2, 3)
print(nested_tuple[1][1]) # Output: 3
UNIT 3
SETS AND DICTIONARIES
Program 1
1. WAP for Creating a Set and Accessing Elements

Creating a set and displaying elements


my_set = {1, 2, 3, 4, 5}
print("Set:", my_set)

# Iterating through the set


for item in my_set:
print(item)
Program 2
2. WAP for Adding Elements to a Set

# Adding elements to a set


my_set = {1, 2, 3}
print("Original Set:", my_set)

# Adding a single element


my_set.add(4)
print("Set after adding 4:", my_set)

# Adding multiple elements using update()


my_set.update([5, 6, 7])
print("Set after adding multiple elements:", my_set)
Program 3
3. WAP for Removing Elements from a Set

# Removing elements from a set


my_set = {1, 2, 3, 4, 5}
print("Original Set:", my_set)

# Removing an element using remove() - Raises error if not found


my_set.remove(3)
print("Set after removing 3:", my_set)

# Removing an element using discard() - No error if not found


my_set.discard(6) # No error even though 6 is not in the set
print("Set after discarding 6:", my_set)
Program 4
4. WAP for Clearing a Set

# Clearing all elements from a set


my_set = {1, 2, 3, 4, 5}
print("Original Set:", my_set)

# Clear the set


my_set.clear()
print("Set after clearing:", my_set) # Output: set()
Program 5
5. WAP to implement Set Union Operation

# Performing union of two sets


set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Union of two sets


union_set = set1.union(set2)
print("Union of set1 and set2:", union_set) # Output: {1, 2, 3, 4, 5}
Program 6
6. WAP to implement Set Intersection Operation

# Performing intersection of two sets


set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Intersection of two sets


intersection_set = set1.intersection(set2)
print("Intersection of set1 and set2:", intersection_set) # Output: {3}
Program 7
7. WAP to implement Set Difference Operation

# Performing difference of two sets


set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Difference of two sets


difference_set = set1.difference(set2)
print("Difference of set1 and set2 (set1 - set2):", difference_set) # Output: {1, 2}
Program 8
8. WAP to implement Set Symmetric Difference Operation

# Performing symmetric difference of two sets


set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Symmetric difference of two sets


sym_diff_set = set1.symmetric_difference(set2)
print("Symmetric Difference of set1 and set2:", sym_diff_set) # Output: {1, 2, 4, 5}
Program 9
9. WAP to implement Checking Subset and Superset

# Checking subset and superset relationships


set1 = {1, 2, 3}
set2 = {1, 2, 3, 4, 5}

# Checking if set1 is a subset of set2


is_subset = set1.issubset(set2)
print("Is set1 a subset of set2?", is_subset) # Output: True

# Checking if set2 is a superset of set1


is_superset = set2.issuperset(set1)
print("Is set2 a superset of set1?", is_superset) # Output: True
Program 10
10. WAP to implement Frozen Sets (Immutable Sets)

# Creating and using a frozenset


my_set = {1, 2, 3}
frozen = frozenset(my_set)
print("Frozen Set:", frozen)

# Trying to modify frozen set (raises error)

frozen.add(4) # This will raise an AttributeError as frozenset is immutable


Program 11
11. Defining and Accessing a Dictionary

# Defining a dictionary
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

# Printing the dictionary


print("Dictionary:", my_dict)

# Accessing elements in a dictionary


my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

# Accessing elements by keys


print("Name:", my_dict['name']) # Output: John
print("Age:", my_dict['age']) # Output: 25
Program 12
12. Adding and Updating Elements in a Dictionary

# Adding and updating elements in a dictionary


my_dict = {'name': 'John', 'age': 25}

# Adding a new key-value pair


my_dict['city'] = 'New York'
print("Dictionary after adding 'city':", my_dict)

# Updating an existing value


my_dict['age'] = 26
print("Dictionary after updating 'age':", my_dict)
Program 13
13. Removing Elements from a Dictionary

# Removing elements from a dictionary


my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

# Removing an element using pop()


removed_value = my_dict.pop('age')
print("Removed value:", removed_value) # Output: 25
print("Dictionary after removal:", my_dict)

# Removing an element using del


del my_dict['city']
print("Dictionary after deleting 'city':", my_dict)
Program 14
14. Iterating Through a Dictionary
# Iterating through a dictionary
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

# Iterating through keys


print("Keys:")
for key in my_dict:
print(key)

# Iterating through values


print("\nValues:")
for value in my_dict.values():
print(value)

# Iterating through key-value pairs


print("\nKey-Value Pairs:")
for key, value in my_dict.items():
print(f"{key}: {value}")
Program 15
15. Dictionary Methods - keys(), values(), items(), get()
# Using dictionary methods keys(), values(), and items()
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

# Getting all keys


keys = my_dict.keys()
print("Keys:", keys) # Using get() to access values safely
age = my_dict.get('age')
# Getting all values print("Age:", age) # Output: 25
values = my_dict.values()
print("Values:", values) # Using get() with a default value if key is not found
salary = my_dict.get('salary', 50000)
# Getting all key-value pairs print("Salary (default):", salary) # Output: 50000
items = my_dict.items()
print("Key-Value Pairs:", items)
UNIT 4
Comprehensions, Functions and Modules
1. List Comprehension

Program 1: Generate even numbers from 1 to 20

even_numbers = [x for x in range(1, 21) if x % 2 == 0]


print(even_numbers)

Program 2: Square of numbers from 1 to 10

squares = [x**2 for x in range(1, 11)]


print(squares)
1. List Comprehension

Program 3: Convert all strings to uppercase

words = ["hello", "world", "python", "rocks"]


uppercase_words = [word.upper() for word in words]
print(uppercase_words)

Program 4: Get the length of each word in a list

words = ["comprehension", "python", "function", "program"]


lengths = [len(word) for word in words]
print(lengths)
1. List Comprehension

Program 5: Create a list of numbers divisible by both 3 and 5

divisible_by_3_and_5 = [x for x in range(1, 51) if x % 3 == 0 and x % 5 == 0]

print(divisible_by_3_and_5)
2. Set Comprehension

Program 1: Create a set of unique characters from a string

input_string = "hello world"


unique_chars = {char for char in input_string}
print(unique_chars)

Program 2: Create a set of squares from 1 to 10

squares_set = {x**2 for x in range(1, 11)}


print(squares_set)
2. Set Comprehension

Program 3: Set of lengths of words in a list

words = ["apple", "banana", "cherry", "kiwi", "mango"]


lengths_set = {len(word) for word in words}
print(lengths_set)

Program 4: Unique remainders when dividing numbers from 1 to 20 by 5

remainders = {x % 5 for x in range(1, 21)}


print(remainders)
2. Set Comprehension

Program 5: Create a set of lowercase vowels from a string

input_string = "The Quick Brown Fox Jumps Over The Lazy Dog"
vowels_set = {char.lower() for char in input_string if char.lower() in 'aeiou'}
print(vowels_set)
3. Dictionary Comprehension

Program 1: Create a dictionary of numbers and their cubes from 1 to 5

cubes_dict = {x: x**3 for x in range(1, 6)}


print(cubes_dict)

Program 2: Create a dictionary of word and its length

words = ["python", "comprehension", "dictionary", "example"]


lengths_dict = {word: len(word) for word in words}
print(lengths_dict)
3. Dictionary Comprehension

Program 3: Create a dictionary mapping numbers to their square roots

import math
sqrt_dict = {x: math.sqrt(x) for x in range(1, 6)}
print(sqrt_dict)

Program 4: Create a dictionary with uppercase letters as keys and their ASCII
values as values

ascii_dict = {chr(x): x for x in range(65, 91)}


print(ascii_dict)
3. Dictionary Comprehension

Program 5: Reverse a dictionary

original_dict = {'a': 1, 'b': 2, 'c': 3}


reversed_dict = {v: k for k, v in original_dict.items()}
print(reversed_dict)
Implement Recursive function
1. WAP for Factorial of a Number (Using Recursion)

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

# Test the function


print(factorial(5))
Implement Recursive function
2. WAP for Fibonacci Series (Using Recursion)

def fibonacci(n):
# Base cases: fibonacci(0) is 0, fibonacci(1) is 1
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)

# Test the function


n=6
for i in range(n):
print(fibonacci(i), end=" ")
Implement Recursive function
3. WAP for Sum of a List (Using Recursion)

def sum_list(lst):
# Base case: empty list returns 0
if len(lst) == 0:
return 0
else:
return lst[0] + sum_list(lst[1:])

# Test the function


numbers = [2, 4, 6, 8, 10]
print(sum_list(numbers))
Implement Recursive function
4. WAP for Reverse a String (Using Recursion)

def reverse_string(s):
# Base case: an empty string or a single character is already reversed
if len(s) == 0:
return s
else:
return s[-1] + reverse_string(s[:-1])

# Test the function


print(reverse_string("hello"))
Implement Recursive function
5. WAP for Power of a Number (Using Recursion)

def power(x, n):


# Base case: x^0 is 1
if n == 0:
return 1
else:
return x * power(x, n - 1)

# Test the function


print(power(2, 4))
UNIT 5
Introduction to Numpy and Pandas
Implement the modules of Pandas and NumPy for Data handling
Program 1: Basic Operations with NumPy Arrays #Calculate column-wise and row-
wise sums
# Import NumPy library col_sum = np.sum(arr, axis=0)
import numpy as np row_sum = np.sum(arr, axis=1)
print("Column-wise sum:", col_sum)
# Create a 2D NumPy array print("Row-wise sum:", row_sum)
arr = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
#Find the maximum and minimum
#Print the shape and size of the array element
print("Array shape:", arr.shape) max_element = np.max(arr)
print("Array size:", arr.size) min_element = np.min(arr)
print("Max element:", max_element)
#Perform element-wise arithmetic operations print("Min element:", min_element)
arr_add = arr + 5
print("Array after adding 5 to each element:\n", arr_add)
Implement the modules of Pandas and NumPy for Data handling
Program 2: Creating and Indexing Pandas DataFrames
# Import Pandas library
import pandas as pd

# Create a DataFrame
data = pd.DataFrame({
'Name': [‘Kuljeet', ‘Singh', ‘Shan', ‘Rahul'],
'Age': [23, 35, 45, 29],
'Score': [85, 95, 88, 92] #Select multiple columns
}) print("Name and Score columns:\n",
data[['Name', 'Score']])
#Display the DataFrame
print("Original DataFrame:\n", data) #Filter rows where Age > 30
filtered_data = data[data['Age'] > 30]
#Select a single column print("Rows where Age > 30:\n",
print("Age column:\n", data['Age']) filtered_data)
Implement the modules of Pandas and NumPy for Data handling
Program 3: Handling Missing Data in Pandas

# Create a DataFrame with missing values #Fill missing values in Score with a
data = pd.DataFrame({ fixed value (e.g., 0)
'Name': [‘Kuljeet', ‘Singh', ‘Shan', ‘Rahul'], data['Score'].fillna(0, inplace=True)
'Age': [23, None, 45, 29], print("DataFrame after filling missing
'Score': [85, 95, None, 92] values:\n", data)
})
#Drop rows with any missing values
#Detect missing values (if any exist)
print("Missing values in the DataFrame:\n", data.dropna(inplace=True)
data.isnull()) print("DataFrame after dropping rows
with missing values:\n", data)
#Fill missing values in Age with the mean of Age
column
data['Age'].fillna(data['Age'].mean(), inplace=True)
Implement the modules of Pandas and NumPy for Data handling
Program 4: Data Aggregation and Grouping with Pandas

# Create a DataFrame
data = pd.DataFrame({
'Department': ['HR', 'Finance', 'IT', 'HR', 'Finance', 'IT'],
'Employee': ['Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Frank'],
'Salary': [50000, 70000, 80000, 45000, 60000, 75000]
})
#Group by 'Department' and calculate the mean salary
mean_salary = data.groupby('Department')['Salary'].mean()
print("Mean salary by department:\n", mean_salary)
Implement the modules of Pandas and NumPy for Data handling
Program 4: Data Aggregation and Grouping with Pandas

#Group by 'Department' and calculate total salary


total_salary = data.groupby('Department')['Salary'].sum()
print("Total salary by department:\n", total_salary)

#Count number of employees in each department


employee_count = data.groupby('Department').size()
print("Number of employees in each department:\n", employee_count)
Implement the modules of Pandas and NumPy for Data handling
Program 5: Reading and Writing CSV Files
import pandas as pd
# Reading data from a CSV file
data = pd.read_csv('sample_data.csv')
print("Data read from CSV file:")
print(data)
# Modifying data
data['New_Column'] = data['Existing_Column'] * 2 # Create a new column
# Saving the modified DataFrame to a new CSV file
data.to_csv('modified_data.csv', index=False)
print("\nData saved to modified_data.csv")
Implement the modules of Pandas and NumPy for Data handling
Program 6: Data Selection with .loc and .iloc

import pandas as pd

# Sample DataFrame
data = pd.DataFrame({
'Name': [‘Kuljeet', ‘Singh', ‘Shan'],
'Age': [24, 27, 22],
'Score': [88, 92, 85]
})
Implement the modules of Pandas and NumPy for Data handling
Program 6: Data Selection with .loc and .iloc

# Selecting rows and columns with .loc


print("Selecting specific rows and columns with .loc:")
print(data.loc[0:1, ['Name', 'Score']]) # Rows 0 and 1, Name and Score columns

# Selecting rows and columns with .iloc


print("\nSelecting specific rows and columns with .iloc:")
print(data.iloc[0:2, 1:3]) # First two rows, second and third columns
Implement the modules of Pandas and NumPy for Data handling
Program 7: Filtering Data Based on Multiple Conditions

import pandas as pd

# Sample DataFrame
data = pd.DataFrame({
'Name': [‘Kuljeet', ‘Singh', ‘Shan', ‘Rahul'],
'Age': [24, 27, 22, 32],
'Score': [88, 92, 85, 76]
})

# Filter rows where Age > 25 and Score > 80


filtered_data = data[(data['Age'] > 25) & (data['Score'] > 80)]
print("Filtered Data:")
print(filtered_data)
Implement the modules of Pandas and NumPy for Data handling
Program 8: Combining Pandas and NumPy for Data Calculations

import pandas as pd
import numpy as np

# Sample DataFrame
data = pd.DataFrame({
'Name': [‘Kuljeet', ‘Singh', ‘Shan'],
'Score1': [88, 92, 85],
'Score2': [79, 85, 90]
})
# Calculating total score and average score using NumPy
data['Total_Score'] = np.add(data['Score1'], data['Score2'])
data['Average_Score'] = np.mean(data[['Score1', 'Score2']], axis=1)
print("DataFrame with Total and Average Scores:")
print(data)
THANK YOU

You might also like