Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the Max value in a two dimensional Array

Tags:

I'm trying to find an elegant way to find the max value in a two-dimensional array. for example for this array:

[0, 0, 1, 0, 0, 1] [0, 1, 0, 2, 0, 0][0, 0, 2, 0, 0, 1][0, 1, 0, 3, 0, 0][0, 0, 0, 0, 4, 0] 

I would like to extract the value '4'. I thought of doing a max within max but I'm struggling in executing it.

like image 963
Shuki Avatar asked Nov 20 '16 08:11

Shuki


People also ask

How do you find the maximum value of a 2D array?

In line 5, we use the amax() method to find the maximum value in the array. Then, we print the maximum value in line 6. From lines 8 to 12, we define a numpy 2D array. In lines 14 and 15, we use the amax() method to find the maximum across the row and column respectively.

How do you find the maximum value of a 2D numpy array?

Find max values along the axis in 2D numpy array | max in rows or columns: If we pass axis=0 in numpy. amax() then it returns an array containing max value for each column i.e. If we pass axis = 1 in numpy.


2 Answers

Another way to solve this problem is by using function numpy.amax()

>>> import numpy as np >>> arr = [0, 0, 1, 0, 0, 1] , [0, 1, 0, 2, 0, 0] , [0, 0, 2, 0, 0, 1] , [0, 1, 0, 3, 0, 0] , [0, 0, 0, 0, 4, 0] >>> np.amax(arr) 
like image 78
Khan Saad Bin Hasan Avatar answered Sep 20 '22 06:09

Khan Saad Bin Hasan


Max of max numbers (map(max, numbers) yields 1, 2, 2, 3, 4):

>>> numbers = [0, 0, 1, 0, 0, 1], [0, 1, 0, 2, 0, 0], [0, 0, 2, 0, 0, 1], [0, 1, 0, 3, 0, 0], [0, 0, 0, 0, 4, 0]  >>> map(max, numbers) <map object at 0x0000018E8FA237F0> >>> list(map(max, numbers))  # max numbers from each sublist [1, 2, 2, 3, 4]  >>> max(map(max, numbers))  # max of those max-numbers 4 
like image 26
falsetru Avatar answered Sep 20 '22 06:09

falsetru