NumPy: Extract all the elements of the third column from a given (4x4) array
Extract Third Column of 4x4 Array
Write a NumPy program to extract all the third column elements from a given (4x4) array.
Pictorial Presentation:
Sample Solution:
Python Code:
Sample Output:
Original array: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]] Extracted data: Third column [ 2 6 10 14]
Explanation:
arra_data = np.arange(0, 16).reshape((4, 4)): It creates a 1-dimensional NumPy array with elements from 0 to 15 (excluding 16) using np.arange(0, 16) and then reshapes it into a 2-dimensional array with 4 rows and 4 columns using .reshape((4, 4)).
print(arra_data[:, 2]): This line prints the third column of the array ‘arra_data’. In this case, it will print [ 2, 6, 10, 14]. The colon : indicates that all rows should be included, and the index 2 corresponds to the third column in the array.
For more Practice: Solve these Related Problems:
- Write a NumPy program to extract the third column from a 4x4 array using slicing with colon notation.
- Create a function that retrieves any specified column from a 2D array and confirms its content.
- Test column extraction on arrays of different sizes to ensure consistent behavior with negative indexing.
- Implement an alternative approach using np.take with axis 1 and compare it to the slicing method.
Python-Numpy Code Editor:
Previous: Write a NumPy program to extract all the elements of the second row from a given (4x4) array.Next: Write a NumPy program to extract first and second elements of the first and second rows from a given (4x4) array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics