Data Science Lab
Data Science Lab
Data Science Lab
1. Creating numpy
What is numpy?
# Performing operations
arr_sum = arr2 + 1 # Add 1 to each element of the 2D array
print("Array with added 1:\n", arr_sum)
import numpy as np
# Create a 1D array with 5 zeros
arr1 = np.zeros(5)
print("1D Array of Zeros:", arr1)
# Create a 2D array with shape (3, 4) filled with zeros
arr2 = np.zeros((3, 4))
print("2D Array of Zeros:\n", arr2)
(c)arrays of ones
import numpy as np
# 1D array of ones
arr1 = np.ones(5)
print("1D Array of Ones:", arr1)
# 2D array of ones
arr2= np.ones((3, 4))
print("2D Array of Ones:\n", arr2)
# 3D array of ones
arr3 = np.ones((2, 3, 4))
print("3D Array of Ones:\n", arr3)
import numpy as np
# Create a 1D NumPy array
array_1d = np.array([1, 2, 3, 4, 5])
# Get the dimensions (shape) of the array
dimensions = array_1d.shape
print("Dimensions of the array:", dimensions)
# Get the total number of elements
total_elements_1d = array_1d.size
print("Total number of elements in the 1D array:",
total_elements_1d)
np.arange
Purpose: Creates a 1D array with evenly spaced values within a
given interval.
Parameters:
o start: (optional) The starting value of the sequence.
import numpy as np
# Create a 3D NumPy array
array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
# Flatten the array
array_flattened = array_3d.flatten()
print("Original 3D array:")
print(array_3d)
print("Flattened 1D array:")
print(array_flattened)
(f) Transpose of a Numpy Array
T attribute
Purpose: Returns the transpose of the array (i.e., rows become
columns and vice versa).
Parameters: None (it's an attribute).
Example: array_2d.T for a 2D array transposes the array.