NumPy, short for Numerical Python, is a fundamental library for data science. It’s used to create and manipulate multidimensional arrays, making it incredibly useful for numerical operations and data analysis.
This article gives you 50 NumPy coding practice problems with solution starting from fundamentals to linear algebra each with a hint, solution, and short explanation so you learn by doing, not just reading.
Below topics are covered in this exercise
- Basics: imports, creation routines, identity matrices, versioning
- Intermediate: Array manipulation and common operations
- Indexing & Slicing: rows, columns, sub-arrays, boolean masks
- Array Operations: element-wise math, dot product, normalization, stats
- Random Numbers: random floats/ints, shuffling, sorting
- Reshaping & Stacking: reshape, flatten, split, tile vs repeat
- Boolean & Filtering: conditional filtering, replace, unique counts, set ops
- Advanced: diagonals, eigenvalues/vectors,
solve, inversion, structured arrays
How to use this guide
- Try the question first.
- Peek at the hint only if needed.
- Write your own solution, then compare with the provided code.
- Read the explanation and tweak inputs (shapes, dtypes) to deepen understanding.
Prerequisites
- Python 3.x
- NumPy installed:
pip install numpy
Use Online Code Editor to solve the exercise.
+ Table of Content (50 Exercises)
Table of contents
- Exercise 1: Create a 1D NumPy array of numbers from 0 to 9
- Exercise 2: Convert 1D array to 2D
- Exercise 3: Print Array Attributes
- Exercise 4: Create a 3×3 NumPy array of all True
- Exercise 5: Extract the documentation of NumPy’s arange() function
- Exercise 6: Create a 1D array filled with zeros and another filled with ones
- Exercise 7: Create a 1D array of 10 evenly spaced values between 5 and 50
- Exercise 8: Convert a Python list into a NumPy array
- Exercise 9: Find the memory size of a NumPy array of numbers from 0 to 9
- Exercise 10: Reverse a 1D NumPy array
- Exercise 11: Create a 3×3 identity matrix
- Exercise 12: Create a 4×4 array and extract its first row and last column
- Exercise 13: Extract Odd Rows and Even Columns
- Exercise 14: Stack arrays horizontally
- Exercise 15: Slice the first two rows and first two columns from a 4×4 array
- Exercise 16: Replace all odd numbers in a NumPy array with -1
- Exercise 17: Get the indices of non-zero elements in an array
- Exercise 18: Find the common items between two arrays
- Exercise 19: Perform arithmetic operations on two NumPy arrays element-wise
- Exercise 20: Matrix multiplication
- Exercise 21: Compute the mean, median, and standard deviation of a NumPy array
- Exercise 22: Remove common items from array
- Exercise 23: Normalize a NumPy array (values between 0 and 1)
- Exercise 24: Get the positions where elements of array a and b match
- Exercise 25: Extract numbers from an array
- Exercise 26: Create a random 3×2 matrix and find its maximum and minimum values
- Exercise 27: Sorting a NumPy array based on a specific column
- Exercise 28: Delete and Insert a Column in a NumPy Array
- Exercise 29: Swap column 1 and 2 in a 2D array
- Exercise 30: Generate 10 random integers between 1 and 100
- Exercise 31: Create a 3×3 array of random integers and sort it row-wise
- Exercise 32: Shuffle an array randomly
- Exercise 33: Create a 5×5 2D array with 1s on the border and 0s inside.
- Exercise 34: Check if an array contains any NaN values.
- Exercise 35: Sort the rows of a 2D array based on the values of the second column
- Exercise 36: Flatten a multi-dimensional NumPy array
- Exercise 37: Stack two arrays vertically and horizontally
- Exercise 38: Split an array into 3 equal parts
- Exercise 39: Perform Addition and Squaring on Arrays
- Exercise 40: Invert a matrix
- Exercise 41: Use boolean indexing to filter values less than a given number
- Exercise 42: Count the number of occurrences of each unique element
- Exercise 43: Find the intersection and union of two arrays
- Exercise 44: Transpose a matrix
- Exercise 45: Compute the eigenvalues and eigenvectors of a matrix
- Exercise 46: Solve a linear equation
- Exercise 47: Create an 8×8 checkerboard pattern using 0s and 1s
- Exercise 48: Find nearest value
- Exercise 49: Convert to object array
- Exercise 50: Compute the mean, median, and standard deviation of a NumPy array
Exercise 1: Create a 1D NumPy array of numbers from 0 to 9
Expected Output:
[0 1 2 3 4 5 6 7 8 9]
+ Hint
Use the np.arange() function.
+ Show Solution
Explanation: np.arange(10) generates values from 0 to 9. The default step is 1.
Exercise 2: Convert 1D array to 2D
Write a code to convert a 1D array to a 2D array with 2 rows.
Given:
import numpy as np
arr = np.arange(6)Code language: Python (python)
Expected Output:
Original Array: [0 1 2 3 4 5]
Reshaped 2x3 Array:
[[0 1 2]
[3 4 5]]
+ Hint
Use reshape(rows, cols) function.
+ Show Solution
Explanation: The .reshape() method is used to give a new shape to an array without changing its data. We specify the new shape as a tuple (rows, columns). Since we want 2 rows and the original array has 6 elements, the new array must have 5 columns (2 * 3 = 6).
Exercise 3: Print Array Attributes
Instructions: Print the following attributes of the array:
- The shape of the array.
- The number of array dimensions.
- The size of each element in bytes.
Given:
import numpy as np
my_array = np.array([[1, 2], [3, 4], [5, 6], [7, 8]], dtype=np.uint16)Code language: Python (python)
Expected Output:
The shape of the array is: (4, 2)
The number of dimensions is: 2
The size of each element in bytes is: 2
+ Show Solution
Explanation: np.array() converts a Python list into a NumPy array. This allows efficient mathematical operations.
Exercise 4: Create a 3×3 NumPy array of all True
Expected Output:
[[ True True True]
[ True True True]
[ True True True]]
+ Hint
Use np.ones() with dtype=bool.
+ Show Solution
Explanation: The np.full() function is a powerful way to create an array of any given shape filled with a specific value. The first argument (3, 3) specifies the shape (3 rows, 3 columns), and the second argument True is the value to fill the array with. The dtype=bool ensures that the array’s data type is boolean.
Exercise 5: Extract the documentation of NumPy’s arange() function
Expected Output:
arange([start,] stop[, step,], dtype=None, *, like=None)
............
+ Hint
Use Python’s np.info() method
+ Show Solution
Explanation: np.info() displays the docstring of a function. It helps understand usage, parameters, and return type.
Exercise 6: Create a 1D array filled with zeros and another filled with ones
Expected Output:
Zeros: [0. 0. 0. 0. 0.]
Ones: [1. 1. 1. 1. 1.]
+ Hint
Use np.zeros() and np.ones().
+ Show Solution
Explanation:
np.ones(5)→ Creates[1. 1. 1. 1. 1.]np.zeros(5)→ Creates[0. 0. 0. 0. 0.]
Exercise 7: Create a 1D array of 10 evenly spaced values between 5 and 50
Expected Output:
[ 5. 10. 15. 20. 25. 30. 35. 40. 45. 50.]
+ Hint
Use np.linspace(start, stop, num).
+ Show Solution
Explanation: np.linspace(5, 50, 10) generates 10 evenly spaced numbers starting from 5 to 50 (inclusive).
Exercise 8: Convert a Python list into a NumPy array
Given:
py_list = [1, 2, 3, 4, 5]Code language: Python (python)
+ Hint
Use np.array(list).
+ Show Solution
Explanation: np.array() converts a Python list into a NumPy array. This allows efficient mathematical operations.
Exercise 9: Find the memory size of a NumPy array of numbers from 0 to 9
Expected Output:
Array: [0 1 2 3 4 5 6 7 8 9]
Memory size in bytes: 80
+ Hint
Use nbytes attribute
+ Show Solution
Explanation: Each element in NumPy has a fixed size. nbytes gives the total memory used by the array
Exercise 10: Reverse a 1D NumPy array
Given:
import numpy as np
arr = np.arange(10)Code language: Python (python)
Expected Output:
[9 8 7 6 5 4 3 2 1 0]
+ Hint
Use slicing [::-1].
+ Show Solution
Explanation: The slice [::-1] steps backwards, effectively reversing the array.
Exercise 11: Create a 3×3 identity matrix
Use tuple unpacking to swap the values of two variables without using a temporary variable.
Expected Output:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
+ Hint
Use np.eye() function.
+ Show Solution
Explanation: An identity matrix has 1s on the diagonal and 0s elsewhere. The np.eye(3) creates a 3×3 identity matrix.
Exercise 12: Create a 4×4 array and extract its first row and last column
Expected Output:
Array:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]
First Row: [1 2 3 4]
Last Column: [ 4 8 12 16]
+ Hint
- Use array indexing
[0]for the first row. - Use slicing
[:, -1]to get last column.
+ Show Solution
Explanation:
np.arange(1, 10).reshape(3, 3)creates a 3×3 array with numbers 1–9.arr[0]selects the first row (indexing starts at 0).
Exercise 13: Extract Odd Rows and Even Columns
Extract an array of odd rows and even columns from below NumPy array.
Problem Breakdown
- Rows: In programming, indexing starts at 0. Odd-indexed rows would be rows 1 and 3.
- Columns: Even-indexed columns would be columns 0 and 2.
Given:
import numpy as np
sampleArray = np.array([
[3, 6, 9, 12],
[15, 18, 21, 24],
[27, 30, 33, 36],
[39, 42, 45, 48],
[51, 54, 57, 60]
])Code language: Python (python)
Expected Output:
New Array with Odd Rows and Even Columns:
[[15 21]
[39 45]]
+ Hint
Use np.hstack().
+ Show Solution
Explanation:
The syntax array[start:stop:step] lets you specify which elements to select.
1::2 for the rows means:
- Start: at index 1 (the second row).
- Stop: Omitted, so it goes to the end of the array.
- Step: 2, meaning it selects every second row. This gives us rows at indices 1 and 3.
::2 for the columns means:
- Start: Omitted, so it defaults to 0 (the first column).
- Stop: Omitted, so it goes to the end.
- Step: 2, meaning it selects every second column. This gives us columns at indices 0 and 2.
By combining these two slices, sampleArray[1::2, ::2], NumPy efficiently creates a new array containing the elements at the intersection of the specified rows and columns.
Exercise 14: Stack arrays horizontally
Given:
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])Code language: Python (python)
Expected Output:
[1 2 3 4 5 6]
+ Hint
Use np.hstack().
+ Show Solution
Explanation: The np.hstack() function stands for “horizontal stack.” It stacks arrays in sequence column-wise, effectively concatenating them along the second axis. For 1D arrays, this simply joins them end-to-end.
Exercise 15: Slice the first two rows and first two columns from a 4×4 array
Write a code to Create a 4×4 NumPy array and extract the first two rows and first two columns.
Expected Output:
Array:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]
First 2 rows and columns:
[[1 2]
[5 6]]
+ Hint
Use slicing [0:2, 0:2].
+ Show Solution
Explanation:
arr[0:2, 0:2]→ selects rows 0–1 and columns 0–1.- The result is a 2×2 sub-matrix.
Exercise 16: Replace all odd numbers in a NumPy array with -1
Expected Output:
Original Array: [ 1 2 3 4 5 6 7 8 9 10]
Modified Array: [-1 2 -1 4 -1 6 -1 8 -1 10]
+ Hint
Use boolean indexing with modulo % to find odd numbers.
+ Show Solution
Explanation:
arr % 2 == 1→ creates a boolean mask for odd numbers.- Assigning
-1replaces all odd values.
Exercise 17: Get the indices of non-zero elements in an array
Given:
import numpy as np
arr = np.array([1, 0, 2, 0, 3, 0, 4])Code language: Python (python)
Expected Output:
Array: [1 0 2 0 3 0 4]
Indices: (array([0, 2, 4, 6]),)
+ Hint
Use np.nonzero().
+ Show Solution
Explanation:
np.nonzero(arr)returns a tuple of indices where elements are non-zero.- In this example →
(array([0, 2, 4, 6]),)meaning non-zero elements are at positions 0, 2, 4, 6.
Exercise 18: Find the common items between two arrays
Given:
import numpy as np
a = np.array([1, 2, 3, 2, 8, 4, 2, 4])
b = np.array([2, 4, 5, 6, 8])Code language: Python (python)
Expected Output:
[2 4 8]
+ Hint
Use the np.intersect1d() function
+ Show Solution
Explanation: The np.intersect1d() function finds the unique common elements between two arrays and returns them in a sorted 1D array. This is a highly efficient way to perform set-like operations on NumPy arrays.
Exercise 19: Perform arithmetic operations on two NumPy arrays element-wise
- Add two NumPy arrays element by element.
- Multiply two NumPy arrays element by element.
Given:
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])Code language: Python (python)
Expected Output:
Element-wise Sum: [5 7 9]
Element-wise multiplication: [ 4 10 18]
+ Hint
- Use the
+operator ornp.add(). - Use the
*operator ornp.multiply().
+ Show Solution
Exercise 20: Matrix multiplication
Write a code to compute the dot product of two NumPy arrays
Given:
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])Code language: Python (python)
Expected Output:
Dot Product: 32
+ Hint
Use np.dot() or @ operator.
+ Show Solution
Explanation:
For matrix multiplication, it’s crucial to distinguish it from element-wise multiplication (*). The @ operator and the np.dot() function are specifically designed for matrix multiplication, following the rules of linear algebra. The result is a new matrix where the value at each position is the dot product of a row from the first matrix and a column from the second.
The dot product is calculated as: 1*4 + 2*5 + 3*6 = 32.
Exercise 21: Compute the mean, median, and standard deviation of a NumPy array
- Mean: Average of numbers.
- Median: Middle value when sorted.
- Standard Deviation: How spread out values are from the mean.
Given:
import numpy as np
arr = np.array([10, 20, 30, 100, 200, 300])Code language: Python (python)
Expected Output:
Mean: 110.0
Median: 65.0
Standard Deviation: 107.08252269472673
+ Hint
Use np.mean(), np.median(), np.std().
+ Show Solution
Exercise 22: Remove common items from array
Given:
import numpy as np
a = np.array([1, 2, 3, 4, 5])
b = np.array([5, 6, 7, 8, 9])Code language: Python (python)
Expected Output:
[1 2 3 4]
+ Hint
Use a boolean mask with the np.in1d() function
+ Show Solution
Explanation:
- The
np.in1d()function checks if each element of the first array is also present in the second array, returning a boolean array. - The
~operator is the bitwise NOT operator, which inverts the boolean mask (e.g.,TruebecomesFalse). We use this inverted mask to select only the elements fromathat are not present inb.
Exercise 23: Normalize a NumPy array (values between 0 and 1)
Given:
import numpy as np
arr = np.array([10, 20, 30, 40, 50])Code language: Python (python)
Expected Output:
Normalized Array: [0. 0.25 0.5 0.75 1. ]
+ Hint
Use formula: arr - arr.min()) / (arr.max() - arr.min()).
+ Show Solution
Explanation:
- Subtract the minimum value so the smallest becomes 0.
- Divide by the range
(max - min)so the largest becomes 1. - This scales all values into
[0, 1].
Exercise 24: Get the positions where elements of array a and b match
Given:
import numpy as np
a = np.array([1, 2, 3, 4, 5])
b = np.array([1, 4, 3, 7, 8])Code language: Python (python)
Expected Output:
(array([0, 2]),)
+ Hint
Use np.where() with a condition.
+ Show Solution
Explanation: The np.where() function returns the indices of elements in an array that satisfy a given condition. In this case, the condition a == b creates a boolean array, and np.where() returns the index of the True value(s)
Exercise 25: Extract numbers from an array
Write a code to extract all numbers from an array that are between 5 and 10 (inclusive).
Given:
import numpy as np
arr = np.arange(15)Code language: Python (python)
Expected Output:
[ 5 6 7 8 9 10]
+ Hint
Combine two boolean masks using the bitwise AND operator (&).
+ Show Solution
Explanation:
- We create two separate boolean masks:
arr >= 5andarr <= 10. - We then use the bitwise AND operator
&to combine them. This creates a new mask whereTrueis only at positions where both conditions are met. - This combined mask is then used to select the desired elements from the original array.
Exercise 26: Create a random 3×2 matrix and find its maximum and minimum values
Expected Output (can vary):
[[0.9 0.05]
[0.7 0.2]
[0.4 0.6]]
Max Value: 0.9
Min Value: 0.05
+ Hint
Use np.random.random() with np.max() and np.min().
+ Show Solution
Explanation: The np.random.rand() function creates an array of a specified shape with random numbers from a uniform distribution over [0, 1). The arguments represent the dimensions of the desired array.
Exercise 27: Sorting a NumPy array based on a specific column
Given:
import numpy as np
sampleArray = np.array([[34, 43, 73], [82, 22, 12], [53, 94, 66]])Code language: Python (python)
Expected Output:
Original array:
[[34 43 73]
[82 22 12]
[53 94 66]]
Sorted array:
[[82 22 12]
[34 43 73]
[53 94 66]]
+ Hint
Get the indices that would sort an array’s elements using np.argsort(). Then, you can use these indices to reorder the rows of the original array
+ Show Solution
Explanation:
The solution uses np.argsort() on the second column to get the correct row order.
sampleArray[:, 1]selects the second column of the array. The:means “select all rows,” and the1specifies the column index (since indexing starts at 0)..argsort(): This method is called on the selected column. It does not sort the column itself but returns the indices that would sort it. For the column[43, 22, 94], the sorted order would be[22, 43, 94], and the corresponding original indices are[1, 0, 2]. This is the output of.argsort().- By using these indices to reorder the rows of the
sampleArray, you get a new array that is sorted based on the values in the second column.
Exercise 28: Delete and Insert a Column in a NumPy Array
Delete the second column from a given array and insert the following new column in its place.
Given:
import numpy as np
sampleArray = np.array([[34,43,73],[82,22,12],[53,94,66]])
newColumnToAdd = np.array([10, 10, 10])Code language: Python (python)
Expected Output:
[[34 10 73]
[82 10 12]
[53 10 66]]
+ Hint
Use np.delete() to remove the second column and then np.insert() to add the new one. Use axis=1 to make sure the operation is performed on the columns.
+ Show Solution
Explanation:
To perform this task, we use a two-step process:
- Delete the column: The
np.delete()function removes a specified column. We pass it the originalsampleArray, the index of the column we want to delete (1), and the argumentaxis=1to tell NumPy that we’re performing the operation on a column. - Insert the new column: The
np.insert()function adds a new column to the array. We pass it the modified array (deletedArray), the index where the new column should go (1), the data for thenewColumn, and again, theaxis=1to ensure it’s treated as a column. NumPy automatically handles broadcasting thenewColumnto the correct shape to fit into the array.
Exercise 29: Swap column 1 and 2 in a 2D array
Given:
import numpy as np
arr = np.arange(9).reshape(3, 3)
# The columns are at index 0, 1, 2. We want to rearrange to 0, 2, 1Code language: Python (python)
Expected Output:
Before
[[0 1 2]
[3 4 5]
[6 7 8]]
After
[[0 2 1]
[3 5 4]
[6 8 7]]
+ Hint
Use advanced indexing with a list of column indices
+ Show Solution
Explanation:
- This is a neat trick using NumPy’s indexing capabilities.
arr[:, [1, 2]]selects all rows (:) and columns 1 and 2. - We then assign the values from
arr[:, [2, 1]], which selects all rows but with columns 2 and 1 in that order. This effectively swaps the data between the two columns.
Exercise 30: Generate 10 random integers between 1 and 100
+ Hint
Use np.random.randint(low, high, size).
+ Show Solution
Explanation:
low=1,high=101(exclusive:- integers from 1 to 100.size=10: generate 10 random integers.
Exercise 31: Create a 3×3 array of random integers and sort it row-wise
+ Hint
Use np.sort() with axis=1.
+ Show Solution
Explanation:
axis=1: sorts elements row by row.- Each row is arranged in ascending order.
Exercise 32: Shuffle an array randomly
Given:
import numpy as np
arr = np.arange(10)Code language: Python (python)
Expected Output (can vary):
Original Array: [0 1 2 3 4 5 6 7 8 9]
Shuffled Array: [4 8 6 1 2 3 5 7 9 0]
+ Hint
Use np.random.shuffle().
+ Show Solution
Explanation:
np.random.shuffle()randomly reorders elements in-place.- Every run gives a different order.
Exercise 33: Create a 5×5 2D array with 1s on the border and 0s inside.
Expected Output:
[[1. 1. 1. 1. 1.]
[1. 0. 0. 0. 1.]
[1. 0. 0. 0. 1.]
[1. 0. 0. 0. 1.]
[1. 1. 1. 1. 1.]]
+ Hint
Create an array of 1s and then use slicing to change the inner values to 0.
+ Show Solution
Explanation:
- We start by creating a 5×5 array of ones using
np.ones(). - Then, we use slicing to access the inner part of the array. The slice
1:-1means “start at index 1 and go up to, but not including, the last element.” - So,
arr[1:-1, 1:-1]selects rows 1 through 3 and columns 1 through 3, which is the inner 3×3 square. We then assign all of these elements to0.
Exercise 34: Check if an array contains any NaN values.
Given:
import numpy as np
a = np.array([1, 2, np.nan, 4, 5])Code language: Python (python)
Expected Output:
True
+ Hint
Use np.isnan() and np.any().
+ Show Solution
Explanation:
- First,
np.isnan(a)creates a boolean array whereTruecorresponds to NaN values. - Then, we use the
.any()method on this boolean array. - The
.any()method returnsTrueif any element of the array isTrue, making it a simple way to check for the presence of NaNs.
Exercise 35: Sort the rows of a 2D array based on the values of the second column
Given:
import numpy as np
arr = np.array([[8, 4, 1],
[5, 2, 7],
[6, 9, 3]])Code language: Python (python)
Expected Output:
[[5 2 7]
[8 4 1]
[6 9 3]]
+ Hint
Use np.argsort() on the second column to get the sorted indices, then use those indices to reorder the rows of the original array.
+ Show Solution
Explanation:
- The
np.argsort()function returns the indices that would sort an array. - We apply it to
arr[:, 1], which is the second column. This gives us the order in which the rows should be arranged to be sorted by that column. - We then use this array of indices to reorder the rows of the original array
arr, resulting in a new sorted array.
Exercise 36: Flatten a multi-dimensional NumPy array
Write a code to Convert a 2D array into a 1D array.
Given:
import numpy as np
arr = np.array([[1, 2], [3, 4], [5, 6]])Code language: Python (python)
Expected Output:
Original Array:
[[1 2]
[3 4]
[5 6]]
Flattened Array: [1 2 3 4 5 6]
+ Hint
Use flatten() or ravel().
+ Show Solution
Explanation:
flatten()returns a copy of the array in 1D form.ravel()can also be used, but it may return a view instead of a copy.
Exercise 37: Stack two arrays vertically and horizontally
Given:
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])Code language: Python (python)
Expected Output:
Vertical Stack:
[[1 2 3]
[4 5 6]]
Horizontal Stack:
[1 2 3 4 5 6]
+ Hint
Use np.vstack() and np.hstack().
+ Show Solution
Explanation:
vstack()→ stacks arrays row-wise (top to bottom).hstack()→ stacks arrays column-wise (side by side).
Exercise 38: Split an array into 3 equal parts
Split a 1D array of 9 elements into 3 equal parts.
Given:
import numpy as np
arr = np.arange(9)Code language: Python (python)
Expected Output:
Original Array: [0 1 2 3 4 5 6 7 8]
Split Arrays: [array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])]
+ Hint
Use np.split(array, parts).
+ Show Solution
Explanation: np.split(arr, 3) divides the array into 3 equal parts. Each part is a smaller NumPy array.
Exercise 39: Perform Addition and Squaring on Arrays
Given:
import numpy as np
arrayOne = np.array([[5, 6, 9], [21, 18, 27]])
arrayTwo = np.array([[15, 33, 24], [4, 7, 1]])Code language: Python (python)
Expected Output:
Result of array addition:
[[20 39 33]
[25 25 28]]
Result with each element squared:
[[ 400 1521 1089]
[ 625 625 784]]
+ Hint
Perform vectorized operations directly on NumPy arrays. This means you can add two arrays together with the + operator and square them using the ** 2 operator
+ Show Solution
Explanation:
- Addition (+): When you use the + operator on two NumPy arrays of the same shape, it performs element-wise addition.
- Squaring (** 2): Similarly, the ** operator works element-wise.
Exercise 40: Invert a matrix
Given:
import numpy as np
arr = np.array([[1, 2], [3, 4]])Code language: Python (python)
Expected Output:
[[-2. 1. ]
[ 1.5 -0.5]]
+ Hint
Use the np.linalg.inv() function.
+ Show Solution
Explanation: The np.linalg module contains a wide range of linear algebra functions. np.linalg.inv() calculates the inverse of a square matrix. The inverse matrix, when multiplied by the original matrix, results in the identity matrix.
Exercise 41: Use boolean indexing to filter values less than a given number
From an array, return values less than 30.
Given:
import numpy as np
arr = np.array([5, 12, 29, 30, 44, 7, 18])Code language: Python (python)
Expected Output:
Values < 30: [ 5 12 29 7 18]
+ Hint
Build a mask arr < 30 and apply it.
+ Show Solution
Explanation: Comparisons on arrays return boolean masks that can be used to filter elements meeting a condition.
Exercise 42: Count the number of occurrences of each unique element
Given:
import numpy as np
arr = np.array([2, 3, 2, 5, 3, 3, 2, 5])Code language: Python (python)
Expected Output:
Value 2 occurs 3 time(s)
Value 3 occurs 3 time(s)
Value 5 occurs 2 time(s)
+ Hint
Use np.unique(..., return_counts=True).
+ Show Solution
Explanation: np.unique returns sorted unique values and, with return_counts=True, the frequency of each value.
Exercise 43: Find the intersection and union of two arrays
- Intersection: elements present in both arrays.
- Union: all unique elements from both arrays, sorted.
Given:
import numpy as np
a = np.array([1, 2, 3, 5, 7])
b = np.array([3, 4, 5, 6, 7])Code language: Python (python)
Expected Output:
Intersection: [3 5 7]
Union: [1 2 3 4 5 6 7]
+ Hint
Use np.intersect1d() and np.union1d().
+ Show Solution
Exercise 44: Transpose a matrix
Transposing a matrix means flipping it over its diagonal.
Given:
import numpy as np
arr = np.array([[1, 2], [3, 4]])Code language: Python (python)
Expected Output:
[[1 3]
[2 4]]
+ Hint
Use the .T attribute or np.transpose().
+ Show Solution
Explanation: The .T attribute is a convenient and commonly used shortcut to get the transposed view of an array without creating a copy. np.transpose() does the same thing but as a function.
Exercise 45: Compute the eigenvalues and eigenvectors of a matrix
For a square matrix, compute its eigenvalues and eigenvectors.
Given:
import numpy as np
A = np.array([[4, 2],
[1, 3]])Code language: Python (python)
Expected Output:
Eigenvalues:
[5. 2.]
Eigenvectors (columns):
[[ 0.89442719 -0.70710678]
[ 0.4472136 0.70710678]]
+ Hint
Use np.linalg.eig().
+ Show Solution
Explanation: np.linalg.eig(A) returns eigenvalues and the corresponding eigenvectors (each column in eigvecs is an eigenvector of A).
Exercise 46: Solve a linear equation
Solve the system of linear equations: x + 2y = 8 and 3x + 4y = 18.
+ Hint
Represent the equations as a matrix problem Ax = b and use np.linalg.solve().
+ Show Solution
Explanation: NumPy is excellent for solving linear equations. We first represent the system as Ax = b, where A is the matrix of coefficients, x is the vector of variables we want to solve for, and b is the vector of constants. np.linalg.solve(A, b) is a very efficient and accurate way to find the x vector.
Exercise 47: Create an 8×8 checkerboard pattern using 0s and 1s
Given:
import numpy as np
arr = np.array([10, 20, 30, 100, 200, 300])Code language: Python (python)
Expected Output:
[[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]]
+ Hint
Use slicing and the modulo operator (%)
+ Show Solution
Explanation:
- We create an 8×8 array of zeros. The trick is in the slicing.
1::2means “start at index 1 and take every second element.”::2means “start at index 0 and take every second element.” - By applying these steps to the rows and columns, we can efficiently set the alternating pattern of 1s without needing a loop.
Exercise 48: Find nearest value
Find the value in an array that is closest to a number 3.
Given:
import numpy as np
arr = np.array([1.5, 2.8, 3.2, 4.1])Code language: Python (python)
Expected Output:
The value closest to 3 is: 2.8
+ Hint
Subtract the given number from the array, take the absolute value, and then find the index of the minimum value using np.abs() and np.argmin().
+ Show Solution
Explanation:
- This is a neat two-step process. First, we perform a vectorized subtraction of the
target_valuefrom the entire array. Then, we take thenp.abs()of the result to get the positive distance from the target for each element. - Finally,
np.argmin()returns the index of the element with the smallest value (i.e., the smallest distance), which we then use to retrieve the corresponding value from the original array.
Exercise 49: Convert to object array
Convert a 1D array to an object array, retaining the original data type of each element.
Given:
import numpy as np
arr = np.array([1, 'a', 3, 4, 5]) Code language: Python (python)
Expected Output:
Zeros: [0. 0. 0. 0. 0.]
Ones: [1. 1. 1. 1. 1.]
+ Hint
Create a new empty object array and fill it with the elements..
+ Show Solution
Explanation:
- A standard NumPy array can only hold elements of the same data type. An object array is a special type of array that can hold Python objects of different types, similar to a regular Python list.
- We create an empty array with
dtype='object'and then use slicing to copy the elements over. This allows us to store mixed data types like integers and strings in a single NumPy array.
Exercise 50: Compute the mean, median, and standard deviation of a NumPy array
Given:
import numpy as np
arr = np.array([10, 20, 30, 100, 200, 300])Code language: Python (python)
Expected Output:
Zeros: [0. 0. 0. 0. 0.]
Ones: [1. 1. 1. 1. 1.]
+ Hint
Use np.mean(), np.median(), np.std().
+ Show Solution
Explanation:
np.ones(5)→ Creates[1. 1. 1. 1. 1.]np.zeros(5)→ Creates[0. 0. 0. 0. 0.]
