Issue
I've just started learning Numpy. I'm already confused as to why the orientation has changed.
Here's my program:
import numpy as np
arr=np.random.random((5,5))
print(arr[-1,:])
which shows:
array([0.79859069, 0.93861609, 0.57585538, 0.87907495, 0.00705881])
Now to find the column with the maximum value on the last row of arr
# Find the max value column in the last row
maxlastvalcol=np.unravel_index(np.argmax(arr[-1,:]),arr[-1,:].shape)
which gives the answer:
(1,)
My understand of numpy is that it's orientation is
(row,column)
So here I've gone from a column to a row. 0.93861609 is in column 1 of that last row. But the output is showing as row 1.
I was expecting to see the result be:
(,1)
What has happened?
Solution
It seems there's a small confusion in understanding the result of np.unravel_index. The function is used to convert a flat index to a tuple of indices in a multi-dimensional array.
In your case, when you use np.argmax(arr[-1, :]), it returns the index of the maximum value in the flattened version of the last row. In this case, the maximum value is at index 1 in the flattened version.
When you apply np.unravel_index to this flat index with respect to the shape of the flattened array (arr[-1, :].shape), it returns the corresponding tuple of indices. In this case, the shape is (5,) because you're dealing with a 1-dimensional array (a row).
So, the result (1,) indicates that the maximum value is at index 1 in the flattened version of the last row of your array.
If you were dealing with a 2D array, the tuple would have two values, one for the row index and another for the column index. However, in this case, since you're working with a 1D array, you get a single-element tuple (1,).
import numpy as np
arr = np.random.random((5, 5))
print(arr[-1, :])
# Find the max value column in the last row
max_last_val_col = np.unravel_index(np.argmax(arr[-1, :]), arr[-1, :].shape)
row_index = -1 # Index for the last row
# Create a tuple with (row, column)
result_tuple = (row_index, max_last_val_col[0])
print(result_tuple)
Now, result_tuple will be a tuple (row_index, column_index) where row_index is the index of the last row (-1 in this case), and column_index is the index of the maximum value in that row. This should give you the desired result.
Answered By - Rudi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.