0% found this document useful (0 votes)
4 views6 pages

Numpy Lab.ipynb - Colaboratory[1]

The document is a Jupyter notebook that demonstrates various functionalities of the NumPy library, including array creation, indexing, operations, statistical functions, linear algebra, and random number generation. It provides examples of creating 1D and 2D arrays, performing mathematical operations, and using aggregation functions. Additionally, it covers advanced topics like masking, boolean logic, fancy indexing, and structured arrays.

Uploaded by

vasanthkv1982004
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)
4 views6 pages

Numpy Lab.ipynb - Colaboratory[1]

The document is a Jupyter notebook that demonstrates various functionalities of the NumPy library, including array creation, indexing, operations, statistical functions, linear algebra, and random number generation. It provides examples of creating 1D and 2D arrays, performing mathematical operations, and using aggregation functions. Additionally, it covers advanced topics like masking, boolean logic, fancy indexing, and structured arrays.

Uploaded by

vasanthkv1982004
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/ 6

11/24/23, 8:00 AM numpy lab.

ipynb - Colaboratory

import numpy as np

# 1) Array creation
# Create a 1D array
arr1d = np.array([1, 2, 3, 4, 5])
print("1D Array:")
print(arr1d)

1D Array:
[1 2 3 4 5]

# Create a 2D array
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("\n2D Array:")
print(arr2d)

output 2D Array:
[[1 2 3]
[4 5 6]
[7 8 9]]

Double-click (or enter) to edit

# 2) Array indexing and selection


# Selecting elements
element = arr2d[1, 1]
print("\nSelected Element:")
print(element)

Selected Element:
5

# Slicing arrays
slice_arr = arr1d[1:4]
print("\nSliced Array:")
print(slice_arr)

Sliced Array:
[2 3 4]

# 3) Array operations
# Element-wise operations
addition = arr1d + 2
print("\nArray after Addition:")
print(addition)

Array after Addition:


[3 4 5 6 7]

# Matrix multiplication
matrix_mult = np.dot(arr2d, arr2d)
print("\nMatrix Multiplication:")
print(matrix_mult)

Matrix Multiplication:
[[ 30 36 42]
[ 66 81 96]
[102 126 150]]

# 4) Statistical functions
# Calculate mean, median, and standard deviation
mean_val = np.mean(arr1d)
median_val = np.median(arr1d)
std_dev = np.std(arr1d)
print(f"\nMean: {mean_val}, Median: {median_val}, Standard Deviation: {std_dev}")

Mean: 3.0, Median: 3.0, Standard Deviation: 1.4142135623730951

https://colab.research.google.com/drive/1WRNLLXKRc1qHjn4ejFcyWCp_6PqTetRf#scrollTo=R_QaNWYRHN0D&printMode=true 1/6
11/24/23, 8:00 AM numpy lab.ipynb - Colaboratory
# 5) Linear algebra
# Compute the eigenvalues and eigenvectors of a matrix
eigenvalues, eigenvectors = np.linalg.eig(arr2d)
print("\nEigenvalues:")
print(eigenvalues)
print("\nEigenvectors:")
print(eigenvectors)

Eigenvalues:
[ 1.61168440e+01 -1.11684397e+00 -1.30367773e-15]

Eigenvectors:
[[-0.23197069 -0.78583024 0.40824829]
[-0.52532209 -0.08675134 -0.81649658]
[-0.8186735 0.61232756 0.40824829]]

# 6) Random number generation


# Generate random numbers from a normal distribution
random_numbers = np.random.normal(loc=0, scale=1, size=(3, 3))
print("\nRandom Numbers from Normal Distribution:")
print(random_numbers)

Random Numbers from Normal Distribution:


[[ 0.55350404 1.90299978 1.13363293]
[ 0.71224238 -0.06116161 2.88152139]
[-1.47850074 -1.05377283 1.61924032]]

# 7) Reshape and concatenate arrays


# Reshape an array
reshaped_arr = np.reshape(arr1d, (5, 1))
print("\nReshaped Array:")
print(reshaped_arr)

Reshaped Array:
[[1]
[2]
[3]
[4]
[5]]

# Concatenate arrays
concatenated_arr = np.concatenate((arr1d, arr1d))
print("\nConcatenated Array:")
print(concatenated_arr)

Concatenated Array:
[1 2 3 4 5 1 2 3 4 5]

# Save and load NumPy array


np.save('numpy_array.npy', arr2d)
loaded_arr = np.load('numpy_array.npy')
print("\nLoaded NumPy Array:")
print(loaded_arr)

Loaded NumPy Array:


[[1 2 3]
[4 5 6]
[7 8 9]]

# 1) Aggregation functions

# Sum of all elements


sum_all = np.sum(arr2d)
print("Sum of all elements:", sum_all)

Sum of all elements: 45

# Sum along columns


sum_columns = np.sum(arr2d, axis=0)
print("\nSum along columns:")
print(sum_columns)

Sum along columns:


[12 15 18]

https://colab.research.google.com/drive/1WRNLLXKRc1qHjn4ejFcyWCp_6PqTetRf#scrollTo=R_QaNWYRHN0D&printMode=true 2/6
11/24/23, 8:00 AM numpy lab.ipynb - Colaboratory

# Sum along rows


sum_rows = np.sum(arr2d, axis=1)
print("\nSum along rows:")
print(sum_rows)

Sum along rows:


[ 6 15 24]

# Mean of all elements


mean_all = np.mean(arr2d)
print("\nMean of all elements:", mean_all)

Mean of all elements: 5.0

# Mean along columns


mean_columns = np.mean(arr2d, axis=0)
print("\nMean along columns:")
print(mean_columns)

Mean along columns:


[4. 5. 6.]

# Mean along rows


mean_rows = np.mean(arr2d, axis=1)
print("\nMean along rows:")
print(mean_rows)

Mean along rows:


[2. 5. 8.]

# Minimum value
min_value = np.min(arr2d)
print("\nMinimum value:", min_value)

Minimum value: 1

# Minimum along columns


min_columns = np.min(arr2d, axis=0)
print("\nMinimum along columns:")
print(min_columns)

Minimum along columns:


[1 2 3]

# Minimum along rows


min_rows = np.min(arr2d, axis=1)
print("\nMinimum along rows:")
print(min_rows)

Minimum along rows:


[1 4 7]

# Maximum value
max_value = np.max(arr2d)
print("\nMaximum value:", max_value)

Maximum value: 9

# Maximum along columns


max_columns = np.max(arr2d, axis=0)
print("\nMaximum along columns:")
print(max_columns)

Maximum along columns:


[7 8 9]

https://colab.research.google.com/drive/1WRNLLXKRc1qHjn4ejFcyWCp_6PqTetRf#scrollTo=R_QaNWYRHN0D&printMode=true 3/6
11/24/23, 8:00 AM numpy lab.ipynb - Colaboratory
# Maximum along rows
max_rows = np.max(arr2d, axis=1)
print("\nMaximum along rows:")
print(max_rows)

Maximum along rows:


[3 6 9]

# Variance
variance = np.var(arr2d)
print("\nVariance of all elements:", variance)

Variance of all elements: 6.666666666666667

# Variance along columns


variance_columns = np.var(arr2d, axis=0)
print("\nVariance along columns:")
print(variance_columns)

Variance along columns:


[6. 6. 6.]

# Variance along rows


variance_rows = np.var(arr2d, axis=1)
print("\nVariance along rows:")
print(variance_rows)

Variance along rows:


[0.66666667 0.66666667 0.66666667]

# Standard deviation
std_dev = np.std(arr2d)
print("\nStandard Deviation of all elements:", std_dev)

Standard Deviation of all elements: 2.581988897471611

# Standard deviation along columns


std_dev_columns = np.std(arr2d, axis=0)
print("\nStandard Deviation along columns:")
print(std_dev_columns)

Standard Deviation along columns:


[2.44948974 2.44948974 2.44948974]

# Standard deviation along rows


std_dev_rows = np.std(arr2d, axis=1)
print("\nStandard Deviation along rows:")
print(std_dev_rows)

Standard Deviation along rows:


[0.81649658 0.81649658 0.81649658]

# 1) Mask and Boolean logic

# Create a mask for values greater than 5


mask_gt_5 = arr2d > 5
print("Mask for values greater than 5:")
print(mask_gt_5)

Mask for values greater than 5:


[[False False False]
[False False True]
[ True True True]]

# Apply the mask


filtered_values = arr2d[mask_gt_5]
print("\nFiltered values greater than 5:")
print(filtered_values)

Filtered values greater than 5:


[6 7 8 9]

https://colab.research.google.com/drive/1WRNLLXKRc1qHjn4ejFcyWCp_6PqTetRf#scrollTo=R_QaNWYRHN0D&printMode=true 4/6
11/24/23, 8:00 AM numpy lab.ipynb - Colaboratory

# Use boolean logic to combine masks


mask_even = arr2d % 2 == 0
combined_mask = np.logical_and(mask_gt_5, mask_even)
print("\nCombined mask for values greater than 5 and even:")
print(combined_mask)

Combined mask for values greater than 5 and even:


[[False False False]
[False False True]
[False True False]]

# Apply the combined mask


filtered_values_combined = arr2d[combined_mask]
print("\nFiltered values for values greater than 5 and even:")
print(filtered_values_combined)

Filtered values for values greater than 5 and even:


[6 8]

# 2) Fancy Indexing

# Create an array of indices


indices = np.array([0, 2])

# Use fancy indexing to select specific rows


selected_rows = arr2d[indices]
print("\nSelected rows using fancy indexing:")
print(selected_rows)

Selected rows using fancy indexing:


[[1 2 3]
[7 8 9]]

# Use fancy indexing to select specific elements


selected_elements = arr2d[indices, [1, 2]]
print("\nSelected elements using fancy indexing:")
print(selected_elements)

Selected elements using fancy indexing:


[2 9]

# 3) Structured Arrays

# Create a structured array with two fields


structured_arr = np.array([(1, 'Alice', 25), (2, 'Bob', 30), (3, 'Charlie', 22)],
dtype=[('ID', int), ('Name', 'U10'), ('Age', int)])
print("\nStructured Array:")
print(structured_arr)

Structured Array:
[(1, 'Alice', 25) (2, 'Bob', 30) (3, 'Charlie', 22)]

# Accessing fields in the structured array


print("\nAccessing fields in the structured array:")
print("IDs:", structured_arr['ID'])
print("Names:", structured_arr['Name'])
print("Ages:", structured_arr['Age'])

Accessing fields in the structured array:


IDs: [1 2 3]
Names: ['Alice' 'Bob' 'Charlie']
Ages: [25 30 22]

https://colab.research.google.com/drive/1WRNLLXKRc1qHjn4ejFcyWCp_6PqTetRf#scrollTo=R_QaNWYRHN0D&printMode=true 5/6
11/24/23, 8:00 AM numpy lab.ipynb - Colaboratory

https://colab.research.google.com/drive/1WRNLLXKRc1qHjn4ejFcyWCp_6PqTetRf#scrollTo=R_QaNWYRHN0D&printMode=true 6/6

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy