0% found this document useful (0 votes)
6 views18 pages

Vedant 2024801005 Experiment 3

The document outlines various experiments using NumPy for data manipulation and analysis, including loading datasets, calculating statistical measures, reshaping arrays, performing arithmetic operations, and filtering data. Each program includes a problem statement, code implementation, and results demonstrating the functionality of NumPy. The experiments cover a range of applications from basic array operations to more complex tasks like matrix multiplication and data visualization.
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)
6 views18 pages

Vedant 2024801005 Experiment 3

The document outlines various experiments using NumPy for data manipulation and analysis, including loading datasets, calculating statistical measures, reshaping arrays, performing arithmetic operations, and filtering data. Each program includes a problem statement, code implementation, and results demonstrating the functionality of NumPy. The experiments cover a range of applications from basic array operations to more complex tasks like matrix multiplication and data visualization.
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
You are on page 1/ 18

BHARATIYA VIDYA BHAVAN’S

SARDAR PATEL INSTITUTE OF TECHNOLOGY


Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai – 400058-India
Department of Computer Science and Engineering

Name Sanchit Ravindra Raut

UID no. 2023800095

Experiment No. 3

AIM: Perform operations using NUMPY on given dataset


Program 1

PROBLEM a. Use NumPy to load the dataset into an array for processing.
STATEMENT :

PROGRAM: import numpy as np

# Load dataset as a NumPy array


arr = np.loadtxt("/content/data.txt",
delimiter=",")
print('loaded dataset \n',arr)

RESULT :
np.loadtxt() reads numerical data from a file, using , as the delimiter to separate values.

Output:

Program 2

PROBLEM # Calculate mean, median, standard deviation, and variance


STATEMENT :

PROGRAM: # Calculate mean, median, standard deviation, and


variance
mean = np.mean(arr) # Average value
median = np.median(arr) # Middle value in sorted
BHARATIYA VIDYA BHAVAN’S
SARDAR PATEL INSTITUTE OF TECHNOLOGY
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai – 400058-India
Department of Computer Science and Engineering

data
std = np.std(arr) # Spread of data
var = np.var(arr) # Variance (square of std
deviation)

print("Mean:", mean)
print("Median:", median)
print("Standard Deviation:", std)
print("Variance:", var)

RESULT :
Built-in NumPy functions compute key statistical measures to analyze data distribution.

Output:

Program 3

PROBLEM # Change the shape of the array to a specified dimension, such as converting a
STATEMENT: 1D

PROGRAM: # Print current shape of array


print(arr.shape)

# Convert array into a 1D array with 60 elements


arr_1d = arr.reshape(60)

# Copy the reshaped array


arr = arr_1d.copy()

print(arr_1d)

RESULT :
The reshape() function modifies the array shape without changing data, and copy() ensures the
original array remains unchanged.
OUTPUT:
BHARATIYA VIDYA BHAVAN’S
SARDAR PATEL INSTITUTE OF TECHNOLOGY
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai – 400058-India
Department of Computer Science and Engineering

Program 4

PROBLEM # Perform element-wise addition, subtraction, multiplication, and division on


STATEMENT: the array

PROGRAM: # Create a copy of the array


arr2 = arr.copy()

# Perform element-wise operations


print('sum : ', arr + arr2) # Addition
print('sub : ', arr - arr2) # Subtraction
print('mul : ', arr * arr2) # Multiplication
print('div : ', arr / arr2) # Division

RESULT:
NumPy applies arithmetic operations element-wise, meaning each element interacts with its
corresponding element.
OUTPUT:

Program 5

PROBLEM # Extract specific elements, rows, or columns from the array using slicing
STATEMENT:
BHARATIYA VIDYA BHAVAN’S
SARDAR PATEL INSTITUTE OF TECHNOLOGY
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai – 400058-India
Department of Computer Science and Engineering

PROGRAM: # Reshape array into 4 rows and 15 columns


arr = arr.reshape(4, 15)

# Extract the first row (all columns of row index


0)
row = arr[0, :]

# Extract the first column (all rows of column


index 0)
col = arr[:, 0]

print('row 1 :', row)


print('col 1 :', col)

RESULT:
NumPy slicing (:) is used to extract specific rows and columns from a reshaped 2D array.
OUTPUT:

Program 6

PROBLEM # Apply a condition to the array to filter out elements that meet certain criteria.
STATEMENT:

PROGRAM: # Select elements that are less than 4


print('elements less than 4 :', arr[arr < 4])

RESULT:
Boolean indexing (arr < 4) filters elements based on a condition, returning values that meet the
criteria.

OUTPUT:
BHARATIYA VIDYA BHAVAN’S
SARDAR PATEL INSTITUTE OF TECHNOLOGY
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai – 400058-India
Department of Computer Science and Engineering

Program 7

PROBLEM # Sort the array in ascending or descending order.


STATEMENT:

PROGRAM: # Convert back to 1D and sort in ascending order


arr = arr.reshape(60)
arr = np.sort(arr)

print(arr)

RESULT:
The np.sort() function arranges the array elements in increasing order.

OUTPUT:

Program 8

PROBLEM # Identify and count the unique elements present in the array.
STATEMENT:

PROGRAM: # Get unique elements in the array


print(np.unique(arr))

# Get unique elements and their counts


uni = np.unique(arr, return_counts=True)
print('unique elements : ', uni[0])
print('unique count : ', uni[1])

RESULT:
np.unique() identifies distinct elements, and return_counts=True returns the frequency of each
unique value.
BHARATIYA VIDYA BHAVAN’S
SARDAR PATEL INSTITUTE OF TECHNOLOGY
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai – 400058-India
Department of Computer Science and Engineering

OUTPUT:

Program 9

PROBLEM # If applicable, perform matrix multiplication between two arrays.


STATEMENT:

PROGRAM: # Reshape array to 15x4 for matrix multiplication


arr = arr.reshape(15, 4)

# Multiply the transposed array with itself


print('multiplication :', np.dot(arr.T, arr))

RESULT:
np.dot() performs matrix multiplication. The array is transposed (arr.T) before multiplication to
match dimensions.

OUTPUT:

Program 10

PROBLEM # Demonstrate NumPy's broadcasting by performing operations between arrays


STATEMENT: of different shapes.

PROGRAM: # Add a smaller array (first 4 elements of arr_1d)


using broadcasting
print(arr + arr_1d[:4])
BHARATIYA VIDYA BHAVAN’S
SARDAR PATEL INSTITUTE OF TECHNOLOGY
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai – 400058-India
Department of Computer Science and Engineering

RESULT:
Broadcasting allows NumPy to expand smaller arrays automatically to match larger arrays for
element-wise operations.

OUTPUT:

Program 11

PROBLEM # Given stock prices for a week, calculate the daily percentage returns and find
STATEMENT: the highest gain and worst loss. Sample stock prices (closing prices for 7 days)

PROGRAM: # Stock prices over a week


prices = np.array([150, 153, 149, 155, 160, 162,
158])

# Compute daily percentage returns


daily_returns = (prices[1:] - prices[:-1]) /
prices[:-1] * 100

# Find highest gain and worst loss


highest_gain = np.max(daily_returns)
BHARATIYA VIDYA BHAVAN’S
SARDAR PATEL INSTITUTE OF TECHNOLOGY
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai – 400058-India
Department of Computer Science and Engineering

worst_loss = np.min(daily_returns)

print("Daily Returns:", daily_returns)


print("Highest Gain:", highest_gain)
print("Worst Loss:", worst_loss)

RESULT:
Stock returns are calculated using (new - old) / old * 100. np.max() and np.min() find the highest
and lowest daily changes.

OUTPUT:

Program 12

PROBLEM # solve equations


STATEMENT: # 3x + 2y -z =-2
# 12x -2y + 4z = -2
# -x + 0.5y - z = 0

PROGRAM: # Define the coefficient matrix


A = np.array([[3, 2, -1],
[12, -2, 4],
[-1, 0.5, -1]])

# Define the constants


b = np.array([-2, -2, 0])

# Solve for x, y, and z


x = np.linalg.solve(A, b)

print("Solution:", x)

RESULT:
np.linalg.solve(A, b) uses matrix algebra to solve the system of linear equations Ax = b.
BHARATIYA VIDYA BHAVAN’S
SARDAR PATEL INSTITUTE OF TECHNOLOGY
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai – 400058-India
Department of Computer Science and Engineering

OUTPUT:

Program 13

PROBLEM # Problem Statement: You have two numpy arrays representing the scores of
STATEMENT: two different exams for the same group of students. Your tasks are:
# a. Create the Arrays: Define two arrays exam1 and exam2 with the given
scores.
# b. Compute the Average Scores: Calculate the average score for each exam.
# c. Combine the Scores: Create a new array where each student's combined
score is the sum of their scores in both exams.
# d. Find the Number of Students with a Combined Score Greater Than 160:
Count how many students have a combined score exceeding 160.

PROGRAM: # Exam scores of students


exam1 = np.array([78, 85, 92, 88, 76, 95, 89, 84])
exam2 = np.array([82, 90, 85, 91, 80, 92, 87, 86])

# Compute average scores


average_exam1 = np.mean(exam1)
average_exam2 = np.mean(exam2)

# Compute total scores for each student


combined_scores = exam1 + exam2

# Count students with total score > 160


students_above_160 = np.sum(combined_scores > 160)

print("Average Exam 1 Score:", average_exam1)


print("Average Exam 2 Score:", average_exam2)
print("Combined Scores:", combined_scores)
print("Students with combined score > 160:",
students_above_160)
BHARATIYA VIDYA BHAVAN’S
SARDAR PATEL INSTITUTE OF TECHNOLOGY
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai – 400058-India
Department of Computer Science and Engineering

RESULT:
np.mean() calculates averages, and np.sum(condition) counts students scoring above 160.

OUTPUT:

Program 14

PROBLEM You are working with data from multiple sensors recorded over time. The data
STATEMENT: is in a 1D array, but you need to reshape it to analyze it as a matrix of sensor
readings over multiple time steps.
# a. Create a 1D Sensor Data Array: Define a 1D array of length 60, where each
value # represents a sensor reading.
# b. Reshape to 3x4x5: Reshape this 1D array into a 3D array with shape
3x4x5, where 3 represents time steps, 4 represents different sensors, and 5
represents readings at each sensor.
# c. Display the Reshaped Array: Show the resulting 3D array.

PROGRAM: # Create a 1D array of sensor readings


sensor_data = np.arange(1, 61)

# Reshape into a 3D array with dimensions (3,4,5)


reshaped_data = sensor_data.reshape(3, 4, 5)

print("Reshaped Sensor Data (3x4x5):")


print(reshaped_data)

RESULT:
np.arange(1, 61) generates values, and reshape(3,4,5) organizes them into a 3D array.

OUTPUT:
BHARATIYA VIDYA BHAVAN’S
SARDAR PATEL INSTITUTE OF TECHNOLOGY
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai – 400058-India
Department of Computer Science and Engineering

Program 15

PROBLEM # Write a NumPy program to create a 3x4 matrix filled with values from 10 to
STATEMENT: 21.

PROGRAM: # Generate a 3x4 matrix with values 10 to 21


matrix = np.arange(10, 22).reshape(3, 4)

print("Matrix (3x4) with values from 10 to 21:")


print(matrix)

RESULT:
np.arange(10, 22) creates numbers from 10 to 21, and reshape(3,4) organizes them into a matrix.

OUTPUT:

Program 16
BHARATIYA VIDYA BHAVAN’S
SARDAR PATEL INSTITUTE OF TECHNOLOGY
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai – 400058-India
Department of Computer Science and Engineering

PROBLEM # Problem Statement: You have an array of temperatures recorded over a week.
STATEMENT: # a. Create the Array: Define a numpy array with the given temperatures.
# b. Find the Average Temperature: Calculate the average temperature over the
week.
# c. Filter Temperatures Above Average: Create an array with temperatures that
are above # the average temperature.
# d. Find the Number of Days with Temperatures Below Freezing: Count how
many days # had temperatures below 0°C.

PROGRAM: # Weekly temperature readings


temperatures = np.array([12, 15, 11, 10, 9, 14,
13])

# Compute average temperature


average_temperature = np.mean(temperatures)

# Filter temperatures above average


above_average = temperatures[temperatures >
average_temperature]

# Count days with temperatures below freezing


(0°C)
below_freezing_count = np.sum(temperatures < 0)

print("Average Temperature:", average_temperature)


print("Temperatures Above Average:",
above_average)
print("Number of Days Below Freezing:",
below_freezing_count)

RESULT:
np.mean() computes the average temperature, Boolean indexing selects values above the average,
and np.sum() counts freezing days.

OUTPUT:
BHARATIYA VIDYA BHAVAN’S
SARDAR PATEL INSTITUTE OF TECHNOLOGY
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai – 400058-India
Department of Computer Science and Engineering

Program 17

PROBLEM # 8) Problem Statement: You are working with grayscale images in a 2D matrix
STATEMENT: format. You need to prepare these images for machine learning models, which
often require the data in a flattened 1D format.
# a. Create a Grayscale Image Matrix: Define a 4x4 grayscale image matrix
with random
# values between 0 and 255.
# b. Flatten the Image Matrix: Convert the 2D image matrix into a 1D array.
# c. Display the Results: Show the original 2D image matrix and the flattened
1D array.

PROGRAM: # Create a 4x4 grayscale image matrix with random


values (0-255)
image_matrix = np.random.randint(0, 256, (4, 4))

# Flatten the 2D image into a 1D array


flattened_image = image_matrix.flatten()

print("Original 2D Image Matrix:")


print(image_matrix)
print("\nFlattened 1D Image Array:")
print(flattened_image)

RESULT:
np.random.randint(0, 256, (4, 4)) generates random grayscale pixel values, and flatten() converts
the 2D matrix into a 1D array.

OUTPUT:
BHARATIYA VIDYA BHAVAN’S
SARDAR PATEL INSTITUTE OF TECHNOLOGY
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai – 400058-India
Department of Computer Science and Engineering

Program 18

PROBLEM Write a NumPy program to append values to the end of an array.


STATEMENT:

PROGRAM: # Define an array


arr = np.array([1, 2, 3, 4])

# Append new values to the array


arr_appended = np.append(arr, [5, 6, 7])

print("Original Array:", arr)


print("Array After Appending:", arr_appended)

RESULT:
np.append() adds new elements to an existing array without modifying the original.

OUTPUT:

Program 19

PROBLEM # Given a 2D array of shape (3, 5) and a 1D array of shape (3, ). Write a Numpy
STATEMENT: program that transposes the 2D array and add the 1D array to each row of the
transposed array

PROGRAM: # Define a 3x5 matrix


array_2d = np.array([[1, 2, 3, 4, 5],
BHARATIYA VIDYA BHAVAN’S
SARDAR PATEL INSTITUTE OF TECHNOLOGY
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai – 400058-India
Department of Computer Science and Engineering

[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15]])

# Define a 1D array
array_1d = np.array([10, 20, 30])

# Transpose the 2D array


transposed_array = array_2d.T

# Add the 1D array to each row of the transposed


array
result_array = transposed_array +
array_1d.reshape(1, -1)

print("Transposed Array:")
print(transposed_array)
print("\nResult after Adding 1D Array to Each
Row:")
print(result_array)

RESULT:
The 2D array is transposed using .T, and reshape(1,-1) adjusts the 1D array shape for broadcasting.

OUTPUT:

Program 20
BHARATIYA VIDYA BHAVAN’S
SARDAR PATEL INSTITUTE OF TECHNOLOGY
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai – 400058-India
Department of Computer Science and Engineering

PROBLEM Write a NumPy program to create a 3D array of shape (3, 3, 3), then reshape it
STATEMENT: into a 1D array using ravel () and finally print the result.

PROGRAM: # Create a 3x3x3 array with random values (0-9)


array_3d = np.random.randint(0, 10, (3, 3, 3))

# Flatten the 3D array to 1D


reshaped_array = array_3d.ravel()

print("Original 3D Array:")
print(array_3d)
print("\nReshaped 1D Array:")
print(reshaped_array)

RESULT:
np.random.randint() generates random numbers, and ravel() flattens the 3D array into a 1D array.

OUTPUT:

Program 21

PROBLEM # 12) Write a NumPy program that creates a 1D array of 16 elements, reshape it
STATEMENT: to (4,4), then change its shape to (2, 8) without changing the underlying data.

PROGRAM: # Create a 1D array with values from 1 to 16


array_1d = np.arange(1, 17)
BHARATIYA VIDYA BHAVAN’S
SARDAR PATEL INSTITUTE OF TECHNOLOGY
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai – 400058-India
Department of Computer Science and Engineering

# Reshape to (4x4)
array_2d = array_1d.reshape(4, 4)

# Reshape to (2x8) without changing data


reshaped_2d = array_1d.reshape(2, 8)

print("Original 1D Array:")
print(array_1d)
print("\nReshaped to (4, 4):")
print(array_2d)
print("\nReshaped to (2, 8):")
print(reshaped_2d)

RESULT:
reshape(4,4) and reshape(2,8) change the structure of the array without modifying its values.

OUTPUT:

Program 22

PROBLEM 13) A company records daily sales for a week. Compute the total revenue, find
STATEMENT: which day had the highest and lowest sales, and calculate the rolling 3-day
average.

PROGRAM: # Daily sales data (in dollars)


sales = np.array([200, 450, 700, 300, 500, 650,
900])
BHARATIYA VIDYA BHAVAN’S
SARDAR PATEL INSTITUTE OF TECHNOLOGY
Bhavan’s Campus, Munshi Nagar, Andheri (West), Mumbai – 400058-India
Department of Computer Science and Engineering

# Calculate total revenue


total_revenue = np.sum(sales)

# Find day with highest and lowest sales


highest_sales_day = np.argmax(sales)
lowest_sales_day = np.argmin(sales)

# Compute rolling 3-day average sales


rolling_3_day_avg = np.convolve(sales,
np.ones(3)/3, mode='valid')

print("Total Revenue:", total_revenue)


print("Highest Sales Day (index):",
highest_sales_day)
print("Lowest Sales Day (index):",
lowest_sales_day)
print("Rolling 3-Day Average Sales:",
rolling_3_day_avg)

RESULT:
np.sum() calculates total sales, np.argmax() and np.argmin() identify the highest and lowest sales
days, and np.convolve() computes a rolling average.

OUTPUT:

CONCLUSION: In this Python lab experiment, I learned how to perform numerical


operations using NumPy. I gained hands-on experience with array manipulation,
mathematical calculations, and handling multidimensional arrays, which are essential for
data analysis. Performed various built-in functions and imported functions of Numpy
Library.

You might also like