Numpy’s key feature is its ability to generate arrays of various shapes and sizes, as well as perform operations on those arrays efficiently. In this case, we want to create a random vector of size 10 using NumPy and replace the maximum value in that vector with 0. There are many methods and techniques available to perform this. let’s discuss a few:
1. Using "where()" and "max()" function :
The where()
function is a powerful tool in NumPy that allows us to search for elements in an array that meet a certain condition, and return their indices as a tuple of arrays. max()
is a function in NumPy that returns the maximum value in an array or along a specified axis.
You can use random.randint()
to create a random vector and where()
to find the index of the maximum value, then replace the max value with 0 using index.
Have a look to the example given below:
2. Using "argsort()" and Indexing :
The argsort()
function in numpy is a method that returns the indices that would sort an array in ascending order. It is a useful function for sorting an array, while still keeping track of the original index positions of the sorted elements.
You can also use random.uniform()
to create a random vector and argsort()
to find the index of the maximum value, then replace the max value with 0.
3. Using "argmax()" function :
The argmax()
function in NumPy returns the indices of the maximum values along a given axis of an array. It returns the index or indices of the maximum value(s) in the array.
The argmax()
function takes one required argument, which is the array to be searched, and one optional argument, axis
.
You can use random.rand()
to create a random vector and argmax()
to find the index of the maximum value. Lets understand this through an example