ASSIGNMENT 2
Q.1) Practice Example on pandas- Write the output.
import pandas as pd
# Data for students
data = {
'Name': ['Kedar', 'Bhavesh', 'Charlie', 'David', 'Mohan'],
'Age': [20, 21, 22, 23, 20],
'Marks': [85, 78, 92, 88, 95]
# Creating DataFrame
df = pd.DataFrame(data)
print(df.head())
Output:
Q.2) Practice program on numpy – Write output.
import numpy as np
# Step 1: Create a 3x3 matrix with values from 1 to 9
matrix = np.arange(1, 10).reshape(3, 3)
print("3x3 Matrix:\n", matrix)
# Step 2: Compute the sum of all elements in the matrix
sum_of_elements = np.sum(matrix)
print("\nSum of all elements in the matrix:", sum_of_elements)
Output:
3x3 Matrix:
[[1 2 3]
[4 5 6]
[7 8 9]]
Sum of all elements in the matrix: 45
Q.3) Practice Example on pandas & numpy : Write the output.
# Import NumPy and Pandas
import numpy as np
import pandas as pd
# Declare an array and perform mathematical operations
arr = np.array([1, 2, 3, 4, 5])
print("Original Array:", arr)
squared_arr = np.square(arr) # Square of each element
mean_value = np.mean(arr) # Mean of the array
print("Squared Array:", squared_arr)
print("Mean Value:", mean_value)
# Create a 2D array (Matrix)
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("\nOriginal Matrix:\n", matrix)
# Perform Transpose of the Matrix
transposed_matrix = np.transpose(matrix)
print("\nTransposed Matrix:\n", transposed_matrix)
# Create a DataFrame using Pandas
data = {
"Name": ["Abha", "Bin", "neil"],
"Age": [25, 30, 22],
"Salary": [50000, 60000, 45000]
df = pd.DataFrame(data)
print("\nOriginal DataFrame:\n", df)
# Add a new column to the DataFrame
df["Department"] = ["HR", "IT", "Finance"]
print("\nDataFrame After Adding New Column:\n", df)
# Filter a column of the DataFrame (e.g., selecting only "Salary" column)
salary_column = df["Salary"]
print("\nFiltered Column (Salary):\n", salary_column)
# Save the DataFrame to a CSV file
df.to_csv("employee_data.csv", index=False)
print("\nDataFrame saved as 'employee_data.csv' successfully!")
Output: