NumPy - Find Indices of Maximum element in large array
NumPy: Performance Optimization Exercise-12 with Solution
Write a NumPy program that creates a large NumPy array and write a function to find the indices of the maximum element using a for loop. Optimize it using NumPy's argmax() function
Sample Solution:
Python Code:
import numpy as np
# Generate a large 1D NumPy array with random integers
large_array = np.random.randint(1, 1000000, size=1000000)
# Function to find the indices of the maximum element using a for loop
def find_max_index_with_loop(arr):
max_index = 0
max_value = arr[0]
for i in range(1, len(arr)):
if arr[i] > max_value:
max_value = arr[i]
max_index = i
return max_index
# Find the index of the maximum element using the for loop method
max_index_with_loop = find_max_index_with_loop(large_array)
# Find the index of the maximum element using NumPy's argmax() function
max_index_with_numpy = np.argmax(large_array)
# Display the results
print(f"Index of maximum element using for loop: {max_index_with_loop}")
print(f"Index of maximum element using NumPy: {max_index_with_numpy}")
Output:
Index of maximum element using for loop: 546157 Index of maximum element using NumPy: 546157
Explanation:
- Importing numpy: We first import the numpy library for array manipulations.
- Generating a large array: A large 1D NumPy array with random integers is generated.
- Defining the function: A function find_max_index_with_loop is defined to find the index of the maximum element using a for loop.
- Finding index with loop: The index of the maximum element is found using the for loop method.
- Finding index with numpy: The index of the maximum element is found using NumPy's built-in argmax() function.
- Displaying results: The results from both methods are printed out to verify correctness.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: NumPy - Cumulative sum of large array using For loop and optimization.
Next: Numpy - Normalize large array using For loop and Vectorized operations.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/numpy/numpy-find-indices-of-maximum-element-in-large-array.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics