Numpy: Top Interview Questions and Answers

NumPy Interview Questions & Answers

Index

1. What is NumPy? 2. How to create a NumPy array? 3. How to create an array of zeros? 4. How to create an array of ones? 5. How to create a range of numbers? 6. How to create an array with evenly spaced values? 7. What is the shape of an array? 8. How to reshape a NumPy array? 9. How to flatten an array? 10. What is the difference between flatten() and ravel()? 11. What is broadcasting in NumPy? 12. How to perform element-wise operations in NumPy? 13. How to calculate the sum of all elements in an array? 14. How to calculate the mean of an array? 15. How to find the standard deviation of an array? 16. How to perform matrix multiplication in NumPy? 17. How to transpose a matrix in NumPy? 18. How to extract specific elements from an array? 19. What is the difference between `np.copy()` and `np.view()`? 20. How to concatenate arrays? 21. How to split an array? 22. How to find unique elements in an array? 23. How to perform logical operations on arrays? 24. How to sort a NumPy array? 25. How to find the index of the maximum value in an array? 26. How to find the index of the minimum value in an array? 27. How to use `np.where()` for conditional operations? 28. How to create a random NumPy array? 29. How to generate random integers in NumPy? 30. How to set the seed for random number generation? 31. How to create a 2D array from a list of lists? 32. How to generate random numbers in NumPy? 33. How to create a range of numbers with a specific step size? 34. How to find the shape of a NumPy array? 35. How to flatten a multi-dimensional array? 36. How to create an identity matrix? 37. How to concatenate two NumPy arrays? 38. How to split an array into multiple sub-arrays? 39. How to find unique elements in an array? 40. How to compute the dot product of two arrays? 41. How to compute the sum of all elements in an array? 42. How to calculate the mean of an array? 43. How to calculate the standard deviation of an array? 44. How to get the indices where a condition is True? 45. How to perform element-wise multiplication of two arrays? 46. How to get the diagonal elements of a 2D array? 47. How to find the rank (number of dimensions) of an array? 48. How to transpose an array? 49. How to find the cumulative sum of an array? 50. How to convert a list of lists to a NumPy array?

1. What is NumPy?

Answer: NumPy is an open-source library for numerical computations in Python. It provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions.

import numpy as np

2. How to create a NumPy array?

Answer: You can create a NumPy array using the np.array() function.

arr = np.array([1, 2, 3])

3. How to create an array of zeros?

Answer: Use np.zeros() to create an array filled with zeros.

zeros = np.zeros((2, 3))

4. How to create an array of ones?

Answer: Use np.ones() to create an array filled with ones.

ones = np.ones((2, 3))

5. How to create a range of numbers?

Answer: Use np.arange() to create an array with regularly incrementing values.

arr = np.arange(0, 10, 2)

6. How to create an array with evenly spaced values?

Answer: Use np.linspace() to create evenly spaced values over a specified interval.

arr = np.linspace(0, 1, 5)

7. What is the shape of an array?

Answer: Shape represents the dimensions of the array.

arr = np.array([[1, 2], [3, 4]])
print(arr.shape)

8. How to reshape a NumPy array?

Answer: Use reshape() to change the dimensions of an array.

arr = np.arange(6)
reshaped = arr.reshape(2, 3)

9. How to flatten an array?

Answer: Use flatten() or ravel() to convert a multi-dimensional array to 1D.

arr = np.array([[1, 2], [3, 4]])
flat = arr.flatten()

10. What is the difference between flatten() and ravel()?

Answer: flatten() returns a copy, while ravel() returns a view (if possible).

arr.flatten(), arr.ravel()

11. What is broadcasting in NumPy?

Answer: Broadcasting is a feature that allows NumPy to perform element-wise operations on arrays of different shapes. NumPy automatically expands the smaller array to match the shape of the larger array.

arr1 = np.array([1, 2, 3])
        arr2 = np.array([10, 20, 30])
        result = arr1 + arr2  # Broadcasting happens here

12. How to perform element-wise operations in NumPy?

Answer: NumPy allows element-wise operations on arrays. You can use operators (+, -, *, /) to perform operations on arrays directly.

arr = np.array([1, 2, 3])
        result = arr * 2  # Each element is multiplied by 2

13. How to calculate the sum of all elements in an array?

Answer: You can calculate the sum of all elements using the np.sum() function.

arr = np.array([1, 2, 3])
        total = np.sum(arr)

14. How to calculate the mean of an array?

Answer: Use np.mean() to calculate the mean of an array.

arr = np.array([1, 2, 3, 4, 5])
        mean = np.mean(arr)

15. How to find the standard deviation of an array?

Answer: Use np.std() to calculate the standard deviation of an array.

arr = np.array([1, 2, 3, 4, 5])
        std_dev = np.std(arr)

16. How to perform matrix multiplication in NumPy?

Answer: Use the np.dot() or @ operator to perform matrix multiplication in NumPy.

arr1 = np.array([[1, 2], [3, 4]])
        arr2 = np.array([[5, 6], [7, 8]])
        result = np.dot(arr1, arr2)  # Matrix multiplication

17. How to transpose a matrix in NumPy?

Answer: Use the .T attribute to transpose a matrix.

arr = np.array([[1, 2], [3, 4]])
        transposed = arr.T

18. How to extract specific elements from an array?

Answer: You can extract specific elements using indexing or slicing.

arr = np.array([1, 2, 3, 4, 5])
        element = arr[2]  # Extract element at index 2
        sub_array = arr[1:4]  # Extract elements from index 1 to 3

19. What is the difference between `np.copy()` and `np.view()`?

Answer: `np.copy()` creates a new array, whereas `np.view()` creates a view of the original array. Changes made to a copy do not affect the original array, but changes to a view affect the original array.

arr = np.array([1, 2, 3])
        copy = arr.copy()  # A new array
        view = arr.view()  # A view of the original array

20. How to concatenate arrays?

Answer: Use np.concatenate() to join two or more arrays along an existing axis.

arr1 = np.array([1, 2, 3])
        arr2 = np.array([4, 5, 6])
        concatenated = np.concatenate((arr1, arr2))

21. How to create an array of zeros?

Answer: Use np.zeros() to create an array of zeros of a given shape.

arr = np.zeros((3, 3))  # 3x3 array of zeros

22. How to create an array of ones?

Answer: Use np.ones() to create an array of ones of a given shape.

arr = np.ones((2, 4))  # 2x4 array of ones

23. What is the difference between `np.array()` and `np.arange()`?

Answer: np.array() creates an array from an existing list, while np.arange() creates an array with a range of numbers, similar to Python's built-in range() function.

arr1 = np.array([1, 2, 3])  # Array from list
        arr2 = np.arange(0, 10, 2)  # Array with a range of values (0, 2, 4, 6, 8)

24. How to reshape an array in NumPy?

Answer: Use the .reshape() method to change the shape of an array without changing its data.

arr = np.array([1, 2, 3, 4, 5, 6])
        reshaped = arr.reshape((2, 3))  # Reshape to 2x3 array

25. How to stack arrays vertically and horizontally?

Answer: Use np.vstack() for vertical stacking and np.hstack() for horizontal stacking.

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

        vertical_stack = np.vstack((arr1, arr2))  # Stacks arrays vertically
        horizontal_stack = np.hstack((arr1, arr2))  # Stacks arrays horizontally

26. How to find the minimum and maximum values in an array?

Answer: Use np.min() to find the minimum and np.max() to find the maximum value of an array.

arr = np.array([1, 2, 3, 4, 5])
        min_value = np.min(arr)  # Minimum value
        max_value = np.max(arr)  # Maximum value

27. How to find the index of the maximum value in an array?

Answer: Use np.argmax() to find the index of the maximum value in an array.

arr = np.array([1, 2, 3, 4, 5])
        index_of_max = np.argmax(arr)  # Index of maximum value

28. How to check if all elements in an array are True?

Answer: Use np.all() to check if all elements of an array evaluate to True.

arr = np.array([True, True, False])
        result = np.all(arr)  # Checks if all elements are True

29. How to check if any element in an array is True?

Answer: Use np.any() to check if any element of an array evaluates to True.

arr = np.array([False, False, True])
        result = np.any(arr)  # Checks if any element is True

30. How to apply a function to each element of an array?

Answer: You can use np.vectorize() to apply a function element-wise on an array.

arr = np.array([1, 2, 3, 4])
        func = np.vectorize(lambda x: x ** 2)
        result = func(arr)  # Squaring each element

31. How to create a 2D array from a list of lists?

Answer: Use np.array() to create a 2D array from a list of lists.

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

32. How to generate random numbers in NumPy?

Answer: Use np.random.rand() for uniform random numbers and np.random.randn() for numbers from a normal distribution.

random_arr = np.random.rand(2, 3)  # Uniform distribution
        random_normal = np.random.randn(2, 3)  # Normal distribution

33. How to create a range of numbers with a specific step size?

Answer: Use np.arange() to create a range of numbers with a specified step size.

arr = np.arange(0, 10, 2)  # Array [0, 2, 4, 6, 8]

34. How to find the shape of a NumPy array?

Answer: Use .shape attribute to find the shape of an array.

arr = np.array([[1, 2, 3], [4, 5, 6]])
        shape = arr.shape  # Output: (2, 3)

35. How to flatten a multi-dimensional array?

Answer: Use the .flatten() method to flatten a multi-dimensional array into a 1D array.

arr = np.array([[1, 2], [3, 4], [5, 6]])
        flattened = arr.flatten()  # Output: [1, 2, 3, 4, 5, 6]

36. How to create an identity matrix?

Answer: Use np.eye() to create an identity matrix of a given size.

identity_matrix = np.eye(3)  # 3x3 identity matrix

37. How to concatenate two NumPy arrays?

Answer: Use np.concatenate() to concatenate arrays along a specified axis.

arr1 = np.array([1, 2, 3])
        arr2 = np.array([4, 5, 6])
        concatenated = np.concatenate((arr1, arr2))  # Output: [1, 2, 3, 4, 5, 6]

38. How to split an array into multiple sub-arrays?

Answer: Use np.split() to split an array into multiple sub-arrays.

arr = np.array([1, 2, 3, 4, 5, 6])
        sub_arrays = np.split(arr, 3)  # Split into 3 sub-arrays

39. How to find unique elements in an array?

Answer: Use np.unique() to find unique elements in an array.

arr = np.array([1, 2, 2, 3, 3, 3])
        unique_elements = np.unique(arr)  # Output: [1, 2, 3]

40. How to compute the dot product of two arrays?

Answer: Use np.dot() to compute the dot product of two arrays.

arr1 = np.array([1, 2])
        arr2 = np.array([3, 4])
        dot_product = np.dot(arr1, arr2)  # Output: 11

41. How to compute the sum of all elements in an array?

Answer: Use np.sum() to compute the sum of all elements in an array.

arr = np.array([1, 2, 3, 4])
        sum_of_elements = np.sum(arr)  # Output: 10

42. How to calculate the mean of an array?

Answer: Use np.mean() to calculate the mean of the elements in an array.

arr = np.array([1, 2, 3, 4])
        mean_value = np.mean(arr)  # Output: 2.5

43. How to calculate the standard deviation of an array?

Answer: Use np.std() to calculate the standard deviation of an array.

arr = np.array([1, 2, 3, 4])
        std_dev = np.std(arr)  # Output: 1.118

44. How to get the indices where a condition is True?

Answer: Use np.where() to get the indices of elements that satisfy a given condition.

arr = np.array([1, 2, 3, 4])
        indices = np.where(arr > 2)  # Output: (array([2, 3]),)

45. How to perform element-wise multiplication of two arrays?

Answer: Use the * operator for element-wise multiplication of arrays.

arr1 = np.array([1, 2, 3])
        arr2 = np.array([4, 5, 6])
        result = arr1 * arr2  # Output: [4, 10, 18]

46. How to get the diagonal elements of a 2D array?

Answer: Use np.diagonal() to extract the diagonal elements of a 2D array.

arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
        diagonal_elements = arr.diagonal()  # Output: [1, 5, 9]

47. How to find the rank (number of dimensions) of an array?

Answer: Use .ndim attribute to find the rank of an array.

arr = np.array([[1, 2, 3], [4, 5, 6]])
        rank = arr.ndim  # Output: 2 (2D array)

48. How to transpose an array?

Answer: Use .T attribute to transpose a 2D array (flip rows and columns).

arr = np.array([[1, 2], [3, 4]])
        transposed = arr.T  # Output: [[1, 3], [2, 4]]

49. How to find the cumulative sum of an array?

Answer: Use np.cumsum() to calculate the cumulative sum of an array.

arr = np.array([1, 2, 3, 4])
        cumulative_sum = np.cumsum(arr)  # Output: [1, 3, 6, 10]

50. How to convert a list of lists to a NumPy array?

Answer: Use np.array() to convert a list of lists to a NumPy array.

list_of_lists = [[1, 2, 3], [4, 5, 6]]
        arr = np.array(list_of_lists)  # Converts list to 2D NumPy array

Comments