NumPy: Extract first and third elements of the first and third rows from a given (4x4) array
Extract First & Third Elements of First/Third Rows
Write a NumPy program to extract the first and third elements of the first and third rows 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: First and third elements of the first and third rows [[ 0 2] [ 8 10]]
Explanation:
In the above exercise -
arra_data = np.arange(0, 16).reshape((4, 4)): This line 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, ::2]): It prints a subarray of ‘arra_data’ by selecting every second row and every second column using the slicing syntax ::2. The : in the slicing syntax indicates selecting all elements, while the 2 after the second colon represents a step of 2, meaning every second element will be selected.
For more Practice: Solve these Related Problems:
- Write a NumPy program to extract the first and third elements from the first and third rows of a 4x4 array.
- Create a function that uses advanced indexing to select non-consecutive elements from specified rows.
- Test the extraction using both slicing and np.take along the specified axis to verify accuracy.
- Implement a solution that dynamically accepts row and column indices to extract a custom submatrix.
Python-Numpy Code Editor:
Previous: Write a NumPy program to extract first and second elements of the first and second rows from a given (4x4) array.Next: Write a NumPy program to extract second and fourth elements of the second and fourth 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