NumPy Practice Questions
Q1. Write a Python program to create a 1D NumPy array with the elements [1, 2, 3, 4, 5].
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
---
Q2. Write a Python program to create a 2D NumPy array with elements [[1, 2, 3], [4, 5, 6]].
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
print(arr_2d)
---
Q3. Write a Python program to generate a 3x3 array of zeros.
zeros = np.zeros((3, 3))
print(zeros)
---
Q4. Write a Python program to generate a 3x3 array of ones.
ones = np.ones((3, 3))
print(ones)
---
Q5. Write a Python program to generate a 3x3 identity matrix.
identity = np.eye(3)
print(identity)
---
Q6. Write a Python program to generate a 3x4 identity-like matrix (non-square).
identity = np.eye(3, 4)
print(identity)
---
Q7. Write a Python program to generate a 3x3 array of random numbers.
rand_nums = np.random.rand(3, 3)
print(rand_nums)
---
Q8. Write a Python program to generate an array of even numbers from 0 to 10.
arr = np.arange(0, 11, 2)
print(arr)
---
Q9. Write a Python program to create an array of 5 evenly spaced numbers between 0 and 10.
arr = np.linspace(0, 10, 5)
print(arr)
---
Q10. Write a Python program to print the shape, size, and data type of the array:
arr = np.array([[1, 2, 3], [4, 5, 6]])
print("Shape:", arr.shape)
print("Size:", arr.size)
print("Data type:", arr.dtype)
---
Q11. Write a Python program to access:
The element in the second row and third column
All rows of column 1
All columns of row 0
The entire second row
arr = np.array([[10, 20, 30], [40, 50, 60]])
print(arr[1, 2])
print(arr[:, 1])
print(arr[0, :])
print(arr[1])
---
Q12. Write a Python program to slice rows:
From index 1 to 3
From start to row 2
From second-to-last to the end
print(arr[1:4])
print(arr[:3])
print(arr[-2:])
---
Q13. Write a Python program to add two 1D NumPy arrays.
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
sum_arr = arr1 + arr2
print(sum_arr)
---
Q14. Write a Python program to find the max, min, and sum of the elements in the array:
arr = np.array([10, 20, 5, 30])
print("Max:", np.max(arr))
print("Min:", np.min(arr))
print("Sum:", np.sum(arr))
---
Q15. Write a Python program to compute the mean, median, and standard deviation.
arr = np.array([1, 2, 3, 4, 5])
print("Mean:", np.mean(arr))
print("Median:", np.median(arr))
print("Std Dev:", np.std(arr))
---
Q16. Write a Python program to reshape an array of numbers from 1 to 9 into a 3x3 matrix.
arr = np.arange(1, 10).reshape(3, 3)
print(arr)
---
Q17. Write a Python program to perform matrix multiplication between two 2x2 matrices.
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
result = np.dot(A, B)
print(result)
---
Q18. Write a Python program to transpose the matrix [[1, 2, 3], [4, 5, 6]].
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.T)