I am trying to find the position of the maximum number in a 2D array. i have used .max() to find the max value but how do i find its position?

Recommended Answers

All 4 Replies

Can you show what you mean by 2d array as there are many alternatives. Looks from tags that you are using numpy. I am not very familiar with it. I know general way of ziping items together with their indexes and sorting the tuples, but numpy should have optimized functions for this.

You have to iterate through the entire array, whether you write you own or use a built in method. Since you also want the max also, go through the array once, storing any number that is larger than the current maximum, along with it's position.

Just a few common Python functions will do ...

# find the index of the largest item in a list
# index starts at zero

a = [77, 123, 18]

a_max = max(a)
ix_max = a.index(a_max)

print(a)       # [77, 123, 18]
print(a_max)   # 123
print(ix_max)  # 1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.