Optimizing Transposition of large NumPy arrays
NumPy: Performance Optimization Exercise-6 with Solution
Write a NumPy program that creates a function to transpose a large 2D NumPy array using nested for loops. Optimize it using NumPy's transpose() function.
Sample Solution:
Python Code:
import numpy as np
# Create a large 2D NumPy array with shape (1000, 1000)
large_array = np.random.rand(1000, 1000)
# Function to transpose a 2D array using nested for loops
def transpose_using_loops(array):
rows, cols = array.shape
transposed_array = np.zeros((cols, rows))
for i in range(rows):
for j in range(cols):
transposed_array[j, i] = array[i, j]
return transposed_array
# Transpose the array using the nested for loops
transposed_loop = transpose_using_loops(large_array)
print("Transposed array using for loop (first 5x5 block):\n", transposed_loop[:5, :5])
# Optimize the transposition using NumPy's transpose() function
transposed_numpy = np.transpose(large_array)
print("Transposed array using NumPy's transpose() function (first 5x5 block):\n", transposed_numpy[:5, :5])
Output:
Transposed array using for loop (first 5x5 block): [[0.40551353 0.40558167 0.86467457 0.58567322 0.8239284 ] [0.3031671 0.45184241 0.5199638 0.52295596 0.52545074] [0.40211577 0.25829343 0.6505094 0.60260168 0.49010591] [0.42364773 0.85953907 0.24050983 0.50997478 0.54401922] [0.94613512 0.94341257 0.30700166 0.25956794 0.17429532]] Transposed array using NumPy's transpose() function (first 5x5 block): [[0.40551353 0.40558167 0.86467457 0.58567322 0.8239284 ] [0.3031671 0.45184241 0.5199638 0.52295596 0.52545074] [0.40211577 0.25829343 0.6505094 0.60260168 0.49010591] [0.42364773 0.85953907 0.24050983 0.50997478 0.54401922] [0.94613512 0.94341257 0.30700166 0.25956794 0.17429532]]
Explanation:
- Create a large array: A 2D NumPy array with shape (1000, 1000) is created using np.random.rand().
- Function with nested for loops: A function transpose_using_loops transposes the array using nested for loops.
- Transpose with loops: The array is transposed using the nested for loops, and the first 5x5 block of the result is printed.
- Optimize with NumPy: The transposition is optimized using NumPy's built-in transpose() function, and the first 5x5 block of the result is printed.
Python-Numpy Code Editor:
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