This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
python max of list of arrays
I have a list of arrays like:
a = [array([ [6,2] , [6,2] ]),array([ [8,3],[8,3] ]),array([ [4,2],[4,2] ])]
I tried max(a) which returns the following error:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
I want it to return either a list or array like:
In: max(a)
Out: [[8,3],[8,3]]
I don't want to convert the inner arrays to list, because the size of the list is very big. Also I purposefully created like that to perform array operations.
In your example you can do something like this:
max(a, key=lambda i: i[0][0])
Depends on what result do you want (what key to use for sorting) you probably have to 'play' with indexes.
http://docs.python.org/2/library/functions.html#max
Anyay, not sure how your previous answer wasn't sufficient, but if you're dealing with numpy arrays, then why isn't the whole lot an array, instead of a list of arrays... Then just use the appropriate numpy function:
from numpy import array
a = array(
[
array([ [6,2], [6,2] ]),
array([ [8,3], [8,3] ]),
array([ [4,2], [4,2] ])
]
)
print a.max(axis=0)
#[[8 3]
# [8 3]]
what about:
max(a, key=lambda x:np.max(x))
# array ([[8, 3], [8, 3]])
please note: the fist max is 'normal max' and the second one is np's max... the logic here is that max uses np.max as it's key for comparison, np.max returns the highest number in the array.
is that what you want?
Related
This question already has answers here:
How to find maximum value in whole 2D array with indices [duplicate]
(3 answers)
Closed 2 years ago.
I have a large 2-dimensional Numpy array which looks a bit like this, and I want to find the indexes of the highest number in the array.
[[0.09911875 0.087047 0.07395894 ... 0.10334793 0.10507131 0.10572167]
[0.09951172 0.08808007 0.07559184 ... 0.0953996 0.09637988 0.09686002]
[0.09908096 0.08856899 0.07680183 ... 0.08633772 0.08709209 0.08753099]
...
[0.16518855 0.1658697 0.16564748 ... 0.16108064 0.15890269 0.15795946]
[0.16250964 0.1616099 0.16255783 ... 0.15931444 0.15753458 0.15655452]
[0.16211866 0.15905266 0.15936445 ... 0.15891747 0.15701842 0.15521818]]
So far, I've tried to use numpy.where() as that function returns a tuple of coordinates but I've only been able to receive an array of tuples, but I want one tuple, the coordinates of the highest number. I've also tried to use other Numpy methods like np.amax, np.max, and np.where but to no success.
To further explain, if you had a small 2D array like this. The largest number is 9.99 and the indexes of the highest number will be (2,2).
[[2.18, 4.01, 3.49, 1.22]
[2.34, 5.23, 5.11, 4.23]
[1.23, 3.42, 9.99, 6.02]
[2.08, 4.01, 3.49, 1.22]]
You could use the numpy.argmax method combined with numpy.unravel:
Here's a minimal working example:
import numpy as np
# create random array
a = np.random.random((8, 8))
# find indexes of the maximum value in this array
np.unravel_index(a.argmax(), a.shape)
# > [4, 3]
You can use:
(x.argmax() // x.shape[1], x.argmax() % x.shape[1])
(2, 2)
All you need to do is to convert the index found by np.argmax() into your matrix indexes. This answer shows how to do that.
This is how you could do it.
import numpy as np
a = np.array([[1, 2, 3], [3, 4, 7], [4, 5, 1]])
max_index = np.argmax(a)
tuple_result = (max_index // a.shape[0], max_index % a.shape[1])
print(tuple_result)
If x is the array then you can try
np.where(x==np.max(x))
This will give you the i,j positions in the array.
What I have is a list where the elements are an array like this:
([1,2,3],[4,5,6],[7,8,9])
What I want is to find the index of an element in this list, something like:
list.index([4,5,6]) #should return 1.
Problem is numpy array comparison throws up errors unless you put something like: (A==B).all()
But this comparison is inside the index function so i can't and don't really want to add the all() bit to the function. Is there an easier solution to this?
Your last error message indicates that you are still mixing lists and arrays. I'll try to recreate the situation:
Make a list of lists. Finding a sublist works just fine:
In [256]: ll=[[1,2,3],[4,5,6],[7,8,9]]
In [257]: ll.index([4,5,6])
Out[257]: 1
Make an array from it - it's 2d.
In [258]: la=np.array(ll)
In [259]: la
Out[259]:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
It does not have an index method
In [260]: la.index([4,5,6])
...
AttributeError: 'numpy.ndarray' object has no attribute 'index'
Make it a list - but we get your ValueError:
In [265]: list(la).index([4,5,6])
...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
That's because list(la) returns a list of arrays, and arrays produce multiple values in == expressions:
In [266]: list(la)
Out[266]: [array([1, 2, 3]), array([4, 5, 6]), array([7, 8, 9])]
The correct way to produce a list from an array is tolist, which returns the original ll list of lists:
In [267]: la.tolist().index([4,5,6])
Out[267]: 1
If you are starting with a numpy array, you can get the result that you want by converting it to a list of lists before using the index() function, e.g.:
import numpy as np
arr = np.array([[1,2,3],[4,5,6],[7,8,9]])
lst = [list(x) for x in arr]
print (lst.index([4,5,6]))
... which gives the expected output 1.
I've got a numpy array, and would like to get the value at a specific element. For example, I might like to access the value at [1,1]
import numpy as np
A = np.arange(9).reshape(3,3)
print A[1,1]
# 4
Now, say I've got the coordinates in an array:
i = np.array([1,1])
How can I index A with my i coordinate array. The following doesn't work:
print A[i]
# [[3 4 5]
# [3 4 5]]
http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html
In Python, x[(exp1, exp2, ..., expN)] is equivalent to x[exp1, exp2, ..., expN]; the latter is just syntactic sugar for the former.
So to get the same result as with A[1,1], you have to index with a tuple.
If you use an ndarray as the indexing object, advanced indexing is triggered:
http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing
Your best bet is A[tuple(i)]. The tuple(i) call just treats i as a sequence and puts the sequence items into a tuple. Note that if your array has more than one dimension, this won't make a nested tuple. It doesn't matter in this case, though.
I have a list of arrays like:
a = [array([6,2]),array([8,3]),array([4,2])]
I tried max(a) which returns the following error:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
I want it to return either a list or array like:
In: max(a)
Out: [8,3]
I don't want to convert the inner arrays to list, because the size of the list is very big. Also I purposefully created like that to perform array operations.
The easiest way is to convert to tuple/lists for the sake of comparison (or implement the comparison yourself):
>>> max(a, key=tuple)
array([8, 3])
Note this is the builtin max and not np.max
EDIT:
For multi dimensional arrays, use the .tolist method:
max(a, key=operator.methodcaller('tolist'))
Defining max on arrays is, as it says in the exception, ambiguous. If we have the following arrays: [6, 2], [5, 1], then I guess the output should be [6, 2], but if we have the following example: [6, 2], [7, 1] what would then the output have to be.
In fact there are so many different definitions of max here. If we take the arrays to be vectors then max can be the magnitude of them, or the vector that has maximum x coord, etc. Max can just as well compare the length of the arrays in the list and return the one with most elements or in the case of a tie the first one of the ones with equal length.
My suggestion is to create a class abstracting your array structures and define the max operation there with exactly the outcome you expect.
To have the max array along with the idx, this is what i'm using now:
a = [array([6,2]),array([8,3]),array([4,2])]
In: max_a = map(max, a)
Out: max_a = [6,8,4]
In: idx = max_a.index(max(max_a))
Out: idx = 1
In: result = a[idx]
Out: reusult = [8,3]
python 3.2
a=[([6,2]),([8,3]),([4,2])]
max(a)
Its working well
I'm trying to get the indices of the maximum element in a Numpy array.
This can be done using numpy.argmax. My problem is, that I would like to find the biggest element in the whole array and get the indices of that.
numpy.argmax can be either applied along one axis, which is not what I want, or on the flattened array, which is kind of what I want.
My problem is that using numpy.argmax with axis=None returns the flat index when I want the multi-dimensional index.
I could use divmod to get a non-flat index but this feels ugly. Is there any better way of doing this?
You could use numpy.unravel_index() on the result of numpy.argmax():
>>> a = numpy.random.random((10, 10))
>>> numpy.unravel_index(a.argmax(), a.shape)
(6, 7)
>>> a[6, 7] == a.max()
True
np.where(a==a.max())
returns coordinates of the maximum element(s), but has to parse the array twice.
>>> a = np.array(((3,4,5),(0,1,2)))
>>> np.where(a==a.max())
(array([0]), array([2]))
This, comparing to argmax, returns coordinates of all elements equal to the maximum. argmax returns just one of them (np.ones(5).argmax() returns 0).
To get the non-flat index of all occurrences of the maximum value, you can modify eumiro's answer slightly by using argwhere instead of where:
np.argwhere(a==a.max())
>>> a = np.array([[1,2,4],[4,3,4]])
>>> np.argwhere(a==a.max())
array([[0, 2],
[1, 0],
[1, 2]])