Data Science Lab
1. Creating numpy
What is numpy?
Numpy is a general-purpose array-processing package. It
provides a high-performance multidimensional array object, and
tools for working with these arrays. It is the fundamental package for
scientific computing with Python
Why is NumPy Faster Than Lists?
NumPy arrays are stored at one continuous place in memory
unlike lists, so processes can access and manipulate them very
efficiently.This is the main reason why NumPy is faster than lists. Also it
is optimized to work with latest CPU architectures.
If you have Python and PIP already installed on a system, then
installation of NumPy is very easy.
Install it using this command: pip install numpy
ndim attribute
Purpose: Returns the number of dimensions (axes) of the array.
Parameters: None (it's an attribute).
Example: array_3d.ndim for a 3D array returns 3.
a) basic nd arrays
import numpy as np
# Creating a 1-dimensional array
arr1 = np.array([1, 2, 3, 4, 5])
print("1D Array:", arr1)
# Creating a 2-dimensional array (matrix)
arr2= np.array([[1, 2, 3], [4, 5, 6]])
print("2D Array:\n", arr2)
# Creating a 3-dimensional array
arr3= np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print("3D Array:\n", arr3)
# Accessing elements
element = arr2[1, 2] # Access the element in row 1, column 2
print("Element at (1, 2):", element)
# Performing operations
arr_sum = arr2 + 1 # Add 1 to each element of the 2D array
print("Array with added 1:\n", arr_sum)
# Checking dimensions and shape
print("dimensions are :", arr1.ndim,arr2.ndim,arr3.ndim)
(b)creating numpy zero arrays
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)
# Create a 3D array with shape (2, 3, 4) filled with zeros
arr3 = np.zeros((2, 3, 4))
print("3D Array of Zeros:\n", arr3)
# Checking dimensions and shape
print("dimensions are :", arr1.ndim,arr2.ndim,arr3.ndim)
(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)
# Checking dimensions and shape
print("dimensions are :", arr1.ndim,arr2.ndim,arr3.ndim)
2.(a) dimensions of Numpy array,(b) shape of Numpy array
&(C) size of Numpy array
np.array
Purpose: Creates a NumPy array from a list or lists.
Parameters:
o object: An array-like object (e.g., list, tuple, or nested lists).
o dtype: (optional) Desired data type of the array elements.
o order: (optional) Whether to store multi-dimensional data in
C (row-major) or Fortran (column-major) order.
Example: np.array([1, 2, 3]) creates a 1D array with elements 1, 2,
3.
shape attribute
Purpose: Returns a tuple representing the dimensions of the
array.
Parameters: None (it's an attribute).
Example: array_1d.shape for a 1D array [1, 2, 3, 4, 5] returns (5,).
size attribute
Purpose: Returns the total number of elements in the array.
Parameters: None (it's an attribute).
Example: array_1d.size for a 1D array [1, 2, 3, 4, 5] returns 5.
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)
# Create a 2D NumPy array
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
# Get the dimensions (shape) of the array
dimensions1 = array_2d.shape
print("Dimensions of the array:", dimensions1)
total_elements_2d = array_2d.size
print("Total number of elements in the 2D array:", total_elements_2d)
# Create a 3D NumPy array
array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
# Get the dimensions (shape) of the array
dimensions2 = array_3d.shape
print("Dimensions of the array:", dimensions2)
total_elements_3d = array_3d.size
print("Total number of elements in the 3D array:", total_elements_3d)
If you only need the number of dimensions, you can use the ndim
attribute:
print("Number of dimensions:", array_3d.ndim)
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.
o stop: The end value of the sequence.
o step: (optional) The spacing between values.
o dtype: (optional) Desired data type of the array elements.
Example: np.arange(12) creates a 1D array with elements from 0
to 11.
reshape method
Purpose: Gives a new shape to an array without changing its
data.
Parameters:
o newshape: A tuple representing the new shape.
Example: array_1d.reshape((3, 4)) reshapes a 1D array with 12
elements into a 2D array with shape (3, 4).
(d) Reshaping a Numpy array
1D Array to 2D Array
import numpy as np
# Create a 1D NumPy array with 12 elements
array_1d = np.arange(12)
# Reshape it to a 2D array with shape (3, 4)
array_2d = array_1d.reshape((3, 4))
print("Reshaped 2D array:")
print(array_2d)
2D Array to 1D Array
# Create a 2D NumPy array
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
# Reshape it to a 1D array
array_1d = array_2d.reshape(-1)
print("Reshaped 1D array:")
print(array_1d)
3D Array to 2D Array
# Create a 3D NumPy array with shape (2, 3, 4)
array_3d = np.arange(24).reshape((2, 3, 4))
print("Original 3D array:")
print(array_3d)
# Reshape it to a 2D array with shape (6, 4)
array_2d = array_3d.reshape((6, 4))
print("Reshaped 2D array:")
print(array_2d)
(e) Flattening a Numpy Array
The flatten method returns a new 1D array and does not modify the
original array. It always returns a copy of the original array.
flatten method
Purpose: Returns a copy of the array collapsed into one
dimension.
Parameters: None.
Example: array_3d.flatten() flattens a 3D array into a 1D array.
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.
# Transpose the array
transposed_array = array_2d.T
print("Original 2D array:")
print(array_2d)
print("Transposed 2D array:")
print(transposed_array)
3. (a) Expanding a NumPy Array
Expanding a NumPy array means adding an extra dimension to the
array. This is commonly done using np.expand_dims.
np.expand_dims
Purpose: Insert a new axis at a specified position.
Parameters:
o a: Input array.
o axis: Position in the expanded axes where the new axis
(dimension) is placed.
import numpy as np
# Create a 1D array
array_1d = np.array([1, 2, 3, 4, 5])
print("Original 1D array:", array_1d)
# Expand the array to 2D (add a new axis at position 0)
expanded_array = np.expand_dims(array_1d, axis=0)
print("Expanded to 2D array:", expanded_array)
# Expand the array to 2D (add a new axis at position 1)
expanded_array = np.expand_dims(array_1d, axis=1)
print("Expanded to 2D array with axis=1:", expanded_array)
(b) Squeezing a NumPy Array
Squeezing a NumPy array means removing single-dimensional entries
from the shape of an array using np.squeeze.
np.squeeze
Purpose: Remove axes of length one from the array.
Parameters:
o a: Input array.
o axis: (optional) Selects a subset of the single-dimensional
entries in the shape.
import numpy as np
# Create a 3D array with a single dimension
array_3d = np.array([[[1, 2, 3], [4, 5, 6]]])
print("Original 3D array with a single dimension:")
print(array_3d)
# Squeeze the array to remove the single dimension
squeezed_array = np.squeeze(array_3d)
print("Squeezed array:")
print(squeezed_array)
(c) Sorting in NumPy Arrays
Sorting arrays in NumPy can be done using np.sort, np.argsort, and the
sort method of NumPy arrays.
np.sort
Purpose: Return a sorted copy of an array.
Parameters:
o a: Input array.
o axis: (optional) Axis along which to sort. Default is -1 (last
axis).
o kind: (optional) Sorting algorithm (e.g., 'quicksort',
'mergesort', 'heapsort').
import numpy as np
# Create an unsorted array
array = np.array([3, 1, 2, 5, 4])
print("Original array:", array)
# Sort the array
sorted_array = np.sort(array)
print("Sorted array:", sorted_array)
*np.argsort
Purpose: Returns the indices that would sort an array.
Parameters:
o a: Input array.
o axis: (optional) Axis along which to sort. Default is -1 (last
axis).
o kind: (optional) Sorting algorithm.
import numpy as np
# Create an unsorted array
array = np.array([3, 1, 2, 5, 4])
print("Original array:", array)
# Get the indices that would sort the array
sorted_indices = np.argsort(array)
print("Indices that would sort the array:", sorted_indices)
*sort method
Purpose: Sorts an array in-place.
Parameters:
o axis: (optional) Axis along which to sort. Default is -1 (last
axis).
o kind: (optional) Sorting algorithm.
import numpy as np
# Create an unsorted array
array = np.array([3, 1, 2, 5, 4])
print("Original array:", array)
# Sort the array in-place
array.sort()
print("Array after in-place sort:", array)