Ani 2
Ani 2
python
Copy code
def is_divisible_by_7(number):
return number % 7 == 0
# Example usage
number = int(input("Enter a number: "))
if is_divisible_by_7(number):
print(f"{number} is divisible by 7")
else:
print(f"{number} is not divisible by 7")
Task 2: Check Voting Eligibility
python
Copy code
def is_eligible_for_voting(age):
return age >= 18
# Example usage
age = int(input("Enter your age: "))
if is_eligible_for_voting(age):
print("You are eligible for voting")
else:
print("You are not eligible for voting")
Task 3: Print Multiplication Table
python
Copy code
def multiplication_table(number):
for i in range(1, 11):
print(f"{number} x {i} = {number * i}")
# Example usage
number = int(input("Enter a number: "))
multiplication_table(number)
Task 4: Convert Decimal to Binary
python
Copy code
def decimal_to_binary(number):
return bin(number).replace("0b", "")
# Example usage
number = int(input("Enter a decimal number: "))
print(f"Binary representation of {number} is {decimal_to_binary(number)}")
Task 5: Create and Start Multiple Threads
python
Copy code
import threading
def runner(id):
print(f"Runner {id} is running")
def create_and_start_threads(num_runners):
threads = []
for i in range(num_runners):
thread = threading.Thread(target=runner, args=(i,))
threads.append(thread)
thread.start()
# Example usage
num_runners = 5
create_and_start_threads(num_runners)
Task 6: Create a Barrier Object
python
Copy code
import threading
def create_barrier(num_runners):
barrier = threading.Barrier(num_runners)
threads = []
for i in range(num_runners):
thread = threading.Thread(target=runner, args=(barrier, i))
threads.append(thread)
thread.start()
# Example usage
num_runners = 5
create_barrier(num_runners)
Task 7: Check if a String is a Palindrome
python
Copy code
def is_palindrome(s):
return s == s[::-1]
# Example usage
s = input("Enter a string: ")
if is_palindrome(s):
print(f"{s} is a palindrome")
else:
print(f"{s} is not a palindrome")
Task 8: Find the Most Frequent Character in a String
python
Copy code
from collections import Counter
def most_frequent_character(s):
return Counter(s).most_common(1)[0][0]
# Example usage
s = input("Enter a string: ")
print(f"The most frequent character in '{s}' is '{most_frequent_character(s)}'")
Task 9: Sum of Two Numbers from Command Line
python
Copy code
import sys
if len(sys.argv) != 3:
print("Usage: python script.py <num1> <num2>")
else:
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])
print(f"The sum of {num1} and {num2} is {num1 + num2}")
Task 10: Demonstrate Various Operators
python
Copy code
def demonstrate_operators(a, b):
print(f"Addition: {a} + {b} = {a + b}")
print(f"Subtraction: {a} - {b} = {a - b}")
print(f"Multiplication: {a} * {b} = {a * b}")
print(f"Division: {a} / {b} = {a / b}")
print(f"Modulus: {a} % {b} = {a % b}")
print(f"Exponentiation: {a} ** {b} = {a ** b}")
print(f"Floor Division: {a} // {b} = {a // b}")
# Example usage
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
demonstrate_operators(a, b)
Task 11: Remove Duplicates from a List
python
Copy code
def remove_duplicates(lst):
return list(set(lst))
# Example usage
lst = [1, 2, 2, 3, 4, 4, 5]
print(f"List after removing duplicates: {remove_duplicates(lst)}")
Task 12: Copy a List Using Various Methods
python
Copy code
def copy_list(lst):
# Method 1: Using slicing
copy1 = lst[:]
# Example usage
lst = [1, 2, 3, 4, 5]
copy1, copy2, copy3 = copy_list(lst)
print(f"Original list: {lst}")
print(f"Copied list (method 1): {copy1}")
print(f"Copied list (method 2): {copy2}")
print(f"Copied list (method 3): {copy3}")
Task 13: Generate an Even List Without List Comprehensions
python
Copy code
def generate_even_list(n):
even_list = []
for i in range(n):
if i % 2 == 0:
even_list.append(i)
return even_list
# Example usage
n = int(input("Enter a number: "))
print(f"Even list: {generate_even_list(n)}")
Task 14: Demonstrate List Comprehension
python
Copy code
def list_comprehension_demo(n):
even_list = [i for i in range(n) if i % 2 == 0]
return even_list
# Example usage
n = int(input("Enter a number: "))
print(f"Even list using list comprehension: {list_comprehension_demo(n)}")
Task 15: Find Tuples with Positive Elements in List of Tuples
python
Copy code
def positive_tuples(tuples_list):
return [t for t in tuples_list if all(x > 0 for x in t)]
# Example usage
tuples_list = [(1, 2), (3, -4), (-1, -2), (5, 6)]
print(f"Tuples with positive elements: {positive_tuples(tuples_list)}")
Task 16: Join Tuples with Similar Initial Element
python
Copy code
from collections import defaultdict
def join_similar_initial(tuples_list):
d = defaultdict(list)
for t in tuples_list:
d[t[0]].append(t)
return [tuple(sum(d[k], ())) for k in d]
# Example usage
tuples_list = [(1, 2), (1, 3), (2, 4), (2, 5)]
print(f"Joined tuples: {join_similar_initial(tuples_list)}")
Task 17: Check if a Set Contains an Element
python
Copy code
def contains_element(s, element):
return element in s
# Example usage
s = {1, 2, 3, 4, 5}
element = int(input("Enter an element: "))
if contains_element(s, element):
print(f"{element} is in the set")
else:
print(f"{element} is not in the set")
Task 18: Find Duplicate Sets in List of Sets
python
Copy code
def find_duplicate_sets(sets_list):
seen = set()
duplicates = set()
for s in sets_list:
if frozenset(s) in seen:
duplicates.add(frozenset(s))
else:
seen.add(frozenset(s))
return [set(s) for s in duplicates]
# Example usage
sets_list = [{1, 2}, {3, 4}, {1, 2}, {5, 6}, {3, 4}]
print(f"Duplicate sets: {find_duplicate_sets(sets_list)}")
Task 19: Safely Create a Nested Directory
python
Copy code
import os
def safely_create_directory(path):
os.makedirs(path, exist_ok=True)
print(f"Directory '{path}' created successfully")
# Example usage
path = "nested/directory/structure"
safely_create_directory(path)
Task 20: Sort a Dictionary by Value
python
Copy code
def sort_dict_by_value(d):
return dict(sorted(d.items(), key=lambda item: item[1]))
# Example usage
d = {"a": 3, "b": 1, "c": 2}
print(f"Sorted dictionary: {sort_dict_by_value(d)}")
Task 21: Sum of All Even Numbers Between 1 and 100
python
Copy code
def sum_even_numbers():
return sum(i for i in range(1, 101) if i % 2 == 0)
# Example usage
print(f"Sum of all even numbers between 1 and 100: {sum_even_numbers()}")
Task 22: Multiply Numbers Greater Than 10 by 5
python
Copy code
def multiply_if_greater_than_10(lst):
for num in lst:
if num > 10:
print(f"{num} x 5 = {num * 5}")
# Example usage
lst = [5, 15, 20, 3, 12]
multiply_if_greater_than_10(lst)
Task 23: User Authentication Class
python
Copy code
import hashlib
class UserAuthentication:
def __init__(self):
self.users = {}
# Example usage
auth = UserAuthentication()
auth.register("user1", "password123")
auth.login("user1", "password123")
auth.reset_password("user1", "password123", "newpassword456")
auth.login("user1", "newpassword456")
Task 24: Car Object
python
Copy code
class Car:
def __init__(self, make, model, year, color, mileage, fuel_level):
self.make = make
self.model = model
self.year = year
self.color = color
self.mileage = mileage
self.fuel_level = fuel_level
# Example usage
my_car = Car("Toyota", "Camry", 2020, "Blue", 15000, 10)
my_car.drive(100)
my_car.refuel(5)
Task 25: Mortgage Calculator
python
Copy code
def mortgage_calculator():
loan_amount = float(input("Enter loan amount: "))
annual_interest_rate = float(input("Enter annual interest rate (in %): ")) /
100
loan_term_years = int(input("Enter loan term (in years): "))
monthly_interest_rate = annual_interest_rate / 12
number_of_payments = loan_term_years * 12
# Example usage
mortgage_calculator()
Task 26: Calculate and Display BMI
python
Copy code
def calculate_bmi():
weight = float(input("Enter your weight in kg: "))
height = float(input("Enter your height in meters: "))
bmi = weight / (height ** 2)
print(f"Your BMI is {bmi:.2f}")
# Example usage
calculate_bmi()
Task 27: Calculate Area of Various Shapes Using Polymorphism
python
Copy code
class Shape:
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14159 * (self.radius ** 2)
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return 0.5 * self.base * self.height
# Example usage
shapes = [Circle(5), Rectangle(4, 6), Triangle(3, 7)]
for shape in shapes:
print(f"Area: {shape.area()}")
Task 28: Animal Sounds Using Polymorphism
python
Copy code
class Animal:
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
print("Woof!")
class Cat(Animal):
def make_sound(self):
print("Meow!")
class Cow(Animal):
def make_sound(self):
print("Moo!")
# Example usage
animals = [Dog(), Cat(), Cow()]
for animal in animals:
animal.make_sound()
Task 29: Basic File Operations
python
Copy code
import shutil
import os
def create_file(filename):
open(filename, 'w').close()
print(f"File '{filename}' created successfully")
def delete_file(filename):
os.remove(filename)
print(f"File '{filename}' deleted successfully")
# Example usage
create_file('test.txt')
copy_file('test.txt', 'copy_test.txt')
move_file('copy_test.txt', 'moved_test.txt')
delete_file('test.txt')
delete_file('moved_test.txt')
Task 30: Sales Data CSV
python
Copy code
import csv
def calculate_total_sales(input_csv, output_csv):
sales = {}
with open(input_csv, mode='r') as file:
reader = csv.reader(file)
next(reader) # Skip header
for row in reader:
product, amount = row
if product in sales:
sales[product] += float(amount)
else:
sales[product] = float(amount)
# Example usage
input_csv = 'sales_data.csv'
output_csv = 'total_sales.csv'
calculate_total_sales(input_csv, output_csv)
Task 31: Prime Check, Factorial, and Fibonacci
python
Copy code
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
def fibonacci(n):
fib_sequence = []
a, b = 0, 1
for _ in range(n):
fib_sequence.append(a)
a, b = b, a + b
return fib_sequence
# Example usage
number = int(input("Enter a number: "))
print(f"{number} is prime: {is_prime(number)}")
print(f"Factorial of {number}: {factorial(number)}")
print(f"First {number} Fibonacci numbers: {fibonacci(number)}")
Task 32: Sum of Numbers from 1 to N
python
Copy code
def sum_of_numbers(n):
return sum(range(1, n + 1))
# Example usage
n = int(input("Enter a number: "))
print(f"Sum of numbers from 1 to {n}: {sum_of_numbers(n)}")
Task 33: Print Multiplication Table of a Given Number
python
Copy code
def multiplication_table(number):
for i in range(1, 11):
print(f"{number} x {i} = {number * i}")
# Example usage
number = int(input("Enter a number: "))
multiplication_table(number)
Task 34: Print List in Reverse Order
python
Copy code
def reverse_list(lst):
return lst[::-1]
# Example usage
lst = [int(x) for x in input("Enter a list of numbers (space-separated):
").split()]
print(f"Reversed list: {reverse_list(lst)}")
Task 35: Reverse a String
python
Copy code
def reverse_string(s):
return s[::-1]
# Example usage
s = input("Enter a string: ")
print(f"Reversed string: {reverse_string(s)}")
Task 36: Generate Prime Numbers up to n
python
Copy code
def generate_primes(n):
primes = []
for num in range(2, n + 1):
if is_prime(num):
primes.append(num)
return primes
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
# Example usage
n = int(input("Enter a number: "))
print(f"Prime numbers up to {n}: {generate_primes(n)}")
Task 37: List Operations
python
Copy code
def find_largest_smallest(lst):
return max(lst), min(lst)
# Example usage
lst1 = [1, 2, 3, 4, 5]
lst2 = [3, 4, 5, 6, 7]
print(f"Largest and smallest elements: {find_largest_smallest(lst1)}")
print(f"Common elements: {find_common_elements(lst1, lst2)}")
print(f"Frequency of elements: {find_frequency(lst1)}")
Task 38: Check Voting Eligibility (Repeated)
python
Copy code
def is_eligible_for_voting(age):
return age >= 18
# Example usage
age = int(input("Enter your age: "))
if is_eligible_for_voting(age):
print("You are eligible for voting")
else:
print("You are not eligible for voting")
Task 39: List Sorting and Average
python
Copy code
def sort_list(lst, descending=False):
return sorted(lst, reverse=descending)
def average_of_list(lst):
return sum(lst) / len(lst)
# Example usage
lst = [int(x) for x in input("Enter a list of numbers (space-separated):
").split()]
print(f"Sorted list (ascending): {sort_list(lst)}")
print(f"Sorted list (descending): {sort_list(lst, descending=True)}")
print(f"Average of the list: {average_of_list(lst)}")
Task 40: Categorize BMI
python
Copy code
def calculate_bmi(weight, height):
return weight / (height ** 2)
def categorize_bmi(bmi):
if bmi < 18.5:
return "Underweight"
elif 18.5 <= bmi < 24.9:
return "Normal weight"
elif 25 <= bmi < 29.9:
return "Overweight"
else:
return "Obesity"
# Example usage
weight = float(input("Enter your weight in kg: "))
height = float(input("Enter your height in meters: "))
bmi = calculate_bmi(weight, height)
print(f"Your BMI is {bmi:.2f}, which is considered {categorize_bmi(bmi)}")
Task 41: Area and Perimeter of a Circle
python
Copy code
def area_of_circle(radius):
return 3.14159 * radius ** 2
def perimeter_of_circle(radius):
return 2 * 3.14159 * radius
# Example usage
radius = float(input("Enter the radius of the circle: "))
print(f"Area of the circle: {area_of_circle(radius)}")
print(f"Perimeter of the circle: {perimeter_of_circle(radius)}")
Task 42: Calculate Area of a Triangle
python
Copy code
def area_of_triangle(base, height):
return 0.5 * base * height
# Example usage
base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
print(f"Area of the triangle: {area_of_triangle(base, height)}")
Task 43: Print All Prime Numbers Within a Given Range
python
Copy code
def primes_in_range(start, end):
return [num for num in range(start, end + 1) if is_prime(num)]
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
# Example usage
start = int(input("Enter the start of the range: "))
end = int(input("Enter the end of the range: "))
print(f"Prime numbers in range {start} to {end}: {primes_in_range(start, end)}")
Task 44: Print All Prime Numbers in an Interval (Repeated)
python
Copy code
def primes_in_interval(start, end):
return [num for num in range(start, end + 1) if is_prime(num)]
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
# Example usage
start = int(input("Enter the start of the interval: "))
end = int(input("Enter the end of the interval: "))
print(f"Prime numbers in interval {start} to {end}: {primes_in_interval(start,
end)}")
Task 45: Basic NumPy Operations
python
Copy code
import numpy as np
def numpy_operations():
a = np.array([1, 2, 3, 4, 5])
b = np.array([6, 7, 8, 9, 10])
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
# Example usage
numpy_operations()
Task 46: Save and Load NumPy Array File
python
Copy code
import numpy as np
def load_numpy_array(filename):
return np.load(filename)
# Example usage
arr = np.array([1, 2, 3, 4, 5])
filename = "array"
save_numpy_array(filename, arr)
loaded_arr = load_numpy_array(filename + ".npy")
print("Loaded array:", loaded_arr)
Task 47: Random NumPy Array and Statistics
python
Copy code
import numpy as np
def random_numpy_array_statistics(size):
arr = np.random.rand(size)
print("Array:", arr)
print("Minimum:", np.min(arr))
print("Maximum:", np.max(arr))
print("Mean:", np.mean(arr))
print("Standard Deviation:", np.std(arr))
# Example usage
size = int(input("Enter the size of the array: "))
random_numpy_array_statistics(size)
Task 48: NumPy Matrix Multiplication
python
Copy code
import numpy as np
def matrix_multiplication():
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
result = np.dot(a, b)
print("Matrix A:\n", a)
print("Matrix B:\n", b)
print("Matrix Multiplication Result:\n", result)
# Example usage
matrix_multiplication()
Task 49: Load CSV into Pandas DataFrame and Basic Operations
python
Copy code
import pandas as pd
def load_and_operate_csv(file_path):
df = pd.read_csv(file_path)
print("DataFrame:\n", df)
# Example usage
file_path = 'data.csv'
load_and_operate_csv(file_path)
Task 50: Create Pandas DataFrame Using Dictionary
python
Copy code
import pandas as pd
def create_dataframe_from_dict(data_dict):
df = pd.DataFrame(data_dict)
print("DataFrame:\n", df)
# Example usage
data_dict = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
create_dataframe_from_dict(data_dict)
Task 51: Use Pandas groupby Function
python
Copy code
import pandas as pd
# Example usage
data = {
'A': ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'],
'B': ['one', 'one', 'two', 'two', 'two', 'one'],
'C': [1, 2, 3, 4, 5, 6],
'D': [2, 3, 4, 5, 6, 7]
}
df = pd.DataFrame(data)
print(group_data(df, ['A', 'B'], {'C': 'sum', 'D': 'mean'}))
Task 52: Filter and Sort Employee Data
python
Copy code
import pandas as pd
# Example usage
data = {
'name': ['Alice', 'Bob', 'Charlie', 'David'],
'department': ['HR', 'Engineering', 'HR', 'Engineering'],
'salary': [50000, 80000, 60000, 75000]
}
df = pd.DataFrame(data)
print(filter_and_sort_employees(df, 'Engineering', sort_by_salary_desc=False))
Task 53: Clean and Preprocess Data
python
Copy code
import pandas as pd
import numpy as np
def clean_data(df):
# Handling missing values
df.fillna(method='ffill', inplace=True)
# Example usage
data = {
'name': ['Alice', 'Bob', 'Charlie', 'David', None],
'department': ['HR', 'Engineering', 'HR', 'Engineering', 'HR'],
'salary': [50000, 200000, 60000, 75000, 80000]
}
df = pd.DataFrame(data)
print(clean_data(df))
Task 54: Handle Duplicates and Validate Email Addresses
python
Copy code
import pandas as pd
import re
def validate_email(email):
return re.match(r"[^@]+@[^@]+\.[^@]+", email) is not None
def clean_customer_data(df):
# Remove duplicates
df.drop_duplicates(inplace=True)
# Example usage
data = {
'name': ['Alice', 'Bob', 'Charlie', 'David', 'Alice'],
'email': ['[email protected]', 'bobexample.com', '[email protected]', '',
'[email protected]']
}
df = pd.DataFrame(data)
print(clean_customer_data(df))
Task 55: Plot Data Using Pandas and Matplotlib
python
Copy code
import pandas as pd
import matplotlib.pyplot as plt
# Example usage
data = {
'Month': ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
'Sales': [200, 300, 250, 400, 350]
}
df = pd.DataFrame(data)
plot_data(df, 'Month', 'Sales')
Task 56: Sales Data Bar Chart
python
Copy code
import pandas as pd
import matplotlib.pyplot as plt
def sales_bar_chart(df):
total_sales = df.groupby('product_category')['sales'].sum()
total_sales.plot(kind='bar')
plt.xlabel('Product Category')
plt.ylabel('Total Sales')
plt.title('Sales by Product Category')
plt.show()
# Example usage
data = {
'product_category': ['A', 'B', 'A', 'C', 'B'],
'sales': [100, 150, 200, 250, 300]
}
df = pd.DataFrame(data)
sales_bar_chart(df)
Task 57: Monthly Sales Line Plot
python
Copy code
import pandas as pd
import matplotlib.pyplot as plt
def monthly_sales_line_plot(df):
monthly_sales = df.groupby('month')['sales'].sum()
monthly_sales.plot(kind='line')
plt.xlabel('Month')
plt.ylabel('Total Sales')
plt.title('Monthly Sales Trend')
plt.show()
# Example usage
data = {
'month': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jan', 'Feb', 'Mar'],
'sales': [200, 300, 250, 400, 350, 150, 200, 100]
}
df = pd.DataFrame(data)
monthly_sales_line_plot(df)
Task 58: Generate Line Plot
python
Copy code
import matplotlib.pyplot as plt
# Example usage
x_values = [1, 2, 3, 4, 5]
y_values = [2, 3, 5, 7, 11]
generate_line_plot(x_values, y_values)
Task 59: Generate Scatter Plot
python
Copy code
import matplotlib.pyplot as plt
# Example usage
x_values = [1, 2, 3, 4, 5]
y_values = [2, 3, 5, 7, 11]
generate_scatter_plot(x_values, y_values)
Task 60: Generate Histogram
python
Copy code
import matplotlib.pyplot as plt
def generate_histogram(data):
plt.hist(data, bins=10)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Histogram')
plt.show()
# Example usage
data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]
generate_histogram(data)
Task 61: Area and Perimeter of a Circle (Repeated)
python
Copy code
def area_of_circle(radius):
return 3.14159 * radius ** 2
def perimeter_of_circle(radius):
return 2 * 3.14159 * radius
# Example usage
radius = float(input("Enter the radius of the circle: "))
print(f"Area of the circle: {area_of_circle(radius)}")
print(f"Perimeter of the circle: {perimeter_of_circle(radius)}")
Task 62: Check Leap Year
python
Copy code
def is_leap_year(year):
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
# Example usage
year = int(input("Enter a year: "))
if is_leap_year(year):
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
Task 63: NumPy Array Operations
python
Copy code
import numpy as np
def numpy_array_operations():
a = np.array([1, 2, 3, 4, 5])
b = np.array([6, 7, 8, 9, 10])
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
# Example usage
numpy_array_operations()
Task 64: NumPy Array with Random Values
python
Copy code
import numpy as np
def random_numpy_array_statistics(size):
arr = np.random.rand(size)
print("Array:", arr)
print("Minimum:", np.min(arr))
print("Maximum:", np.max(arr))
print("Mean:", np.mean(arr))
print("Standard Deviation:", np.std(arr))
# Example usage
size = int(input("Enter the size of the array: "))
random_numpy_array_statistics(size)
Task 65: Load CSV into Pandas DataFrame and Basic Operations
python
Copy code
import pandas as pd
def load_and_operate_csv(file_path):
df = pd.read_csv(file_path)
print("DataFrame:\n", df)
# Example usage
file_path = 'data.csv'
load_and_operate_csv(file_path)
Task 66: Pandas groupby Function (Repeated)
python
Copy code
import pandas as pd
# Example usage
data = {
'A': ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'],
'B': ['one', 'one', 'two', 'two', 'two', 'one'],
'C': [1, 2, 3, 4, 5, 6],
'D': [2, 3, 4, 5, 6, 7]
}
df = pd.DataFrame(data)
print(group_data(df, ['A', 'B'], {'C': 'sum', 'D': 'mean'}))
Task 67: Clean and Preprocess Data (Repeated)
python
Copy code
import pandas as pd
import numpy as np
def clean_data(df):
# Handling missing values
df.fillna(method='ffill', inplace=True)
# Example usage
data = {
'name': ['Alice', 'Bob', 'Charlie', 'David', None],
'department': ['HR', 'Engineering', 'HR', 'Engineering', 'HR'],
'salary': [50000, 200000, 60000, 75000, 80000]
}
df = pd.DataFrame(data)
print(clean_data(df))