Finding and indexing maximum value - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Finding and indexing maximum value (/thread-13630.html) |
Finding and indexing maximum value - BlueBall - Oct-24-2018 I have a large grid, but let's say it is 4 cells wide and 3 cells high. Index of the first cell is 0 and it starts bottom left, finishes in the upper right corner with index 11 .Each cell has a value. So we have a df :cell;value 0;8 1;2 2;1 3;6 4;4 5;6 6;7 7;1 8;2 9;5 10;3 11;5 How do I identify cell that has a max value around itself? - For corner cells this means that we look at the observed cell and all three around it. - For middle cells we observe the cell and all 8 around it. The goal is to find the cell with max value, add to df a new column and to the cell with max value return 1 and all the others 0 .For the upper example this would mean: cell;value;maxValue 0;8;1 1;2;0 2;1;0 3;6;0 4;4;0 5;6;0 6;7;1 7;1;0 8;2;0 9;5;0 10;3;0 11;5;0 EDIT: This is the "image" of the grid and its values, respectively. IMAGE LINK Anyone? Should I use IF command and go with if (i+1) and (i-1) and ... ?
RE: Finding and indexing maximum value - ichabod801 - Oct-24-2018 I would come up with a list of possible offsets. Loop through the cells. For each cell, loop through the offsets, and get the other cells at those offsets, adding them up. You'll need a check to make sure you're not checking outside the matrix (or a try/except block). Keep track of the highest total and what it's index is as you go along. RE: Finding and indexing maximum value - perfringo - Oct-25-2018 (Oct-24-2018, 03:00 PM)ichabod801 Wrote: I would come up with a list of possible offsets. Loop through the cells. For each cell, loop through the offsets, and get the other cells at those offsets, adding them up. You'll need a check to make sure you're not checking outside the matrix (or a try/except block). Keep track of the highest total and what it's index is as you go along. Implemented on matrices it will look something like that: def maximum_around(matrix, r, c): """Find maximum value with indices around value in matrix.""" values = list() coordinates = list() offset = (0, 1, -1) indices = ((i, j) for i in offset for j in offset) next(indices, None) for rec in indices: try: row = r - 1 + rec[0] col = c - 1 + rec[1] if 0 <= row and 0 <= col: value = matrix[row][col] values.append(value) coordinates.append([row, col]) except IndexError: continue return {max(values): coordinates[values.index(max(values))]}
>>> n = [[-1, -2, -3], [-4, -5, -6], [-7, -8, -9] ] >>> maximum_around(n, 3, 3) {-5: [1, 1]} |