Numpy Basics

Creating numpy arrays

import numpy as np

#creating 1d array
np1d = np.array([1,2,3,4,5])
print(np1d)
## [1 2 3 4 5]
#creating 2d array
np2d = np.array([[1,2,3],[4,5,6]])
print(np2d)
## [[1 2 3]
##  [4 5 6]]
#creating 2darray with datatype
np2d = np.array([[1,2,3],[4,5,6]],dtype=np.int32)
print(np2d)
## [[1 2 3]
##  [4 5 6]]
#creating 3darray
np3d = np.array([[[1,2,3],[4,5,6],[7,8,9]]],np.bool)
print(np3d)
## [[[ True  True  True]
##   [ True  True  True]
##   [ True  True  True]]]

Creating with placeholders

import numpy as np

#creating array of zeros
np_zeros = np.zeros((3,4))
print(np_zeros)
#creating array of ones
np_ones = np.ones((3,4))
print(np_ones)

#creating an array with evenly spaced values
np_arange = np.arange(0,10,2)
print(np_arange)

#creating constatns array
np_const = np.full((2,3),9)
print(np_const)

#creating 2 by 2 identity matrix
np_iden = np.eye(2,dtype=np.int8)
print(np_iden)

#creating array with random values
np_random = np.random.random((2,3))
print(np_random)

#creating an empty array
np_empty = np.empty((3,4))
print(np_empty)

Reshaping Arrays

import numpy as np

np_1d = np.array([1,2,3,4,5,6])

#get the shape of the array
print(np_1d.shape)

#reshape the array
np_2d = np_1d.reshape((3,2))
print(np_2d)

Inspecting Arrays

np_dataset2 = np.random.randint(5,size=(3,3,3))
#inpsecting your arrays
print("shape" ,np_dataset2.shape) #shape of the array
print(len(np_dataset2)) # length of the array
print(np_dataset2.ndim) #number of dimensions of the array
print(np_dataset2.size) #number of array elements
print(np_dataset2.dtype) #data type of the array elements
print(np_dataset2.dtype.name) #name of datatype
print(np_dataset2.astype(float)) #convert array to different types

Copying Arrays

np_dataset = np.random.randint(5,size=(3,3,3))

#copying arrays
np_dataset1 = np_dataset.view()
#creating copy of the array
np_dataset2 = np.copy(np_dataset1)
#creating deep copy
np_dataset2 = np_dataset2.copy()

Mathematical operations


#mathematical operations
a = np.random.randint(4,size=(2,2))
b = np.random.randint(4,size=(2,2))
c = np.add(a,b)
d = np.subtract(a,b)
e = np.multiply(a,b)
f = np.divide(a,b)
g = np.exp(b) #calculate e to the power x for each element where e = 2.71 eular constant
h = np.sin(a)
i = np.log(a) #element wise natural logarithm
print(i)
j = np.dot(np.array([1,2,3]),np.array([1,2,3]))
print("j",j)

Indexing and Slicing

import numpy as np

arr1 = np.array([[1,2,3,4,5],[7,8,9,10,11]])

#element at 1 row and 2 column
print(arr1[1,2])

#elements at 2 column
print(arr1[:,1])

#elements at 2 row
print(arr1[1,:])



#Slicing in 1 darray
a = np.random.randint(10,size=(10))
print(a)

#slicing from index 2 to 5 excluding 5
print(a[2:5])

#slicing from index start to 4 excluding 4
print(a[:4])

#slicing from index 3 to end
print(a[3:]) 

#slicing the entire array
print(a[:])

#slicing with a step of 2
print(a[::2])

#slicing with negative step (reversing array)
print(a[::-1])

#slicing the 2d array
a = np.random.randint(10,size=(2,5))

#slicing the first two rows and all columns
print(a[:2 , :])

#slicing the last row and the last two column
print(a[-1 ,-1:])

#slicing the middle subarray
print(a[1:3,1:3])

#slicing with step of 2 in clumns and 1 in rows
print(a[::2,::1])

Array Manipulation

#Array manipulation
#tranposing an array
a = np.random.randint(10,size=(2,5))
b = np.transpose(a)
print(b)

#flaten the array
c=a.ravel()
print(c)

##change array shape
d=a.reshape(5,2)
print(d)

#resize
e = np.resize(d,(7,))
print(e)

Matrix operations

import numpy as np

#matrix operations 
#matrix multiplication or dot product
arr1 = np.array([[1,2],[3,4]])
arr2 = np.array([[1,2],[3,4]])

dot_product = np.dot(arr1,arr2)
print(dot_product)

#element wise multiplication
arr3 = arr1*arr2
print(arr3)

#Tranpose of a matrix
arr_t = arr3.T

Statistical operations

import numpy as np

arr1 = np.array([1,2,3,4,5])
#mean
print(np.mean(arr1))

#median
print(np.median(arr1))

#standard deviation
print(np.std(arr1))

#calculate sum
print(np.sum(arr1))

#calculate min
print(np.mean(arr1))

#calculate max
print(np.max(arr1))

import numpy as np

data = np.array([[1, 2, 3, 4, 5], 
                 [2, 4, 6, 8, 10]])

print(np.corrcoef(data))

correlation_matrix = np.corrcoef(data.T)
print(correlation_matrix)

Concatenation and stacking

import numpy as np

#concatenate arrays along axis
arr1 = np.array([1,2])
arr2 = np.array([1,2])

print(np.concatenate((arr1,arr2)))

#stack arrays vertically
print(np.vstack((arr1,arr2)))

#stack arrays horizontaly
print(np.hstack((arr1,arr2)))

Broadcasting

#broadcasting allows you to perform element wise opearations on array of different shapes
import numpy as np

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

broadcast_sum = arr1 + arr2
print(broadcast_sum)

loading and saving

import numpy as np

arr1 = np.array([1,2,3])
np.save("arr1.npy",arr1)

arr2 = np.load("arr1.npy")
print(arr1)
print(arr2)
  • What is NumPy, and why is it commonly used in Python programming?
  • How do you create and manipulate NumPy arrays?
  • What are the different data types supported by NumPy?
  • How can you perform operations on NumPy arrays, such as addition, subtraction, and multiplication?
  • What functions do you use to reshape and flatten NumPy arrays?
  • Explain the difference between a list and a NumPy array.
  • How do you handle missing values in NumPy arrays?
  • How numpy array is useful for solving Linear Algebra problems

Getting common elements in two numpy arrays

import numpy as np
arr1 = np.random.randint(10,size=(2,5))
arr2 = np.random.randint(10,size=(2,5))
print(np.intersect1d(arr1,arr2))
[4 6 7]

Swapping rows of a numpy array

import numpy as np
arr1 = np.random.randint(10,size=(2,5))
print(arr1)
arr1[[0,1]] = arr1[[1,0]]
print(arr1)
[[7 3 9 5 5]
 [2 8 7 7 7]]
[[2 8 7 7 7]
 [7 3 9 5 5]]

Reverse columns of 2d Array

import numpy as np

# Create a 2D NumPy array
arr = np.array([[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]])

# Reverse the columns of the array
reversed_columns = arr[:, ::-1]

print(reversed_columns)
[[3 2 1]
 [6 5 4]
 [9 8 7]]
import numpy as np

# Create a NumPy array with float values
arr = np.array([1.123456, 2.654321, 3.987654])

# Set print options to show only 3 decimal places
np.set_printoptions(precision=3)

# Print the array
print(arr)
[1.123 2.654 3.988]
  • What is NumPy, and why is it commonly used in Python programming?
  • How do you create and manipulate NumPy arrays?
  • What are the different data types supported by NumPy?
  • How can you perform operations on NumPy arrays, such as addition, subtraction, and multiplication?
  • What functions do you use to reshape and flatten NumPy arrays?
  • Explain the difference between a list and a NumPy array.
  • How do you handle missing values in NumPy arrays?
  • How numpy array is useful for solving Linear Algebra problems