-->

How to find max values from multiple lists?

2020-07-26 11:59发布

问题:

I have multiple lists (or numpy arrays) of the same size and I want to return an array of the same size with the max value at each point.

For example,

A = [[0,1,0,0,3,0],[1,0,0,2,0,3]]
B = [[1,0,0,0,0,4],[0,5,6,0,1,1]]
C = numpy.zeros_like(A)
for i in xrange(len(A)):
    for j in xrange(len(A[0])):
        C[i][j] = max(A[i][j],B[i][j])

The result is C = [[1,1,0,0,3,4],[1,5,6,2,1,3]]

This works fine, but is not very efficient - especially for the size of arrays that I have and the number of arrays I need to compare. How can I do this more efficiently?

回答1:

Use numpy.maximum:

numpy.maximum(x1, x2[, out])
Element-wise maximum of array elements.

Compare two arrays and returns a new array containing the element-wise maxima. If one of the elements being compared is a nan, then that element is returned. If both elements are nans then the first is returned. The latter distinction is important for complex nans, which are defined as at least one of the real or imaginary parts being a nan. The net effect is that nans are propagated.



回答2:

A non Numpy Solution

>>> [map(max,a,b,c) for a,b,c in zip(A,B,C)]
[[1, 1, 0, 0, 3, 4], [1, 5, 6, 2, 1, 3]]
>>> 


回答3:

If you needed to compare more that 2 arrays you could do the following

from numpy import random, dstack

A = random.random((2,5))
B = random.random((2,5))
C = random.random((2,5))

stacked_arrays = dstack((A,B,C))
max_of_stack = stacked_arrays.max(2)

dstack will turn your 2D arrays into a 3D stack of 2D arrays

The 2 inside of the parenthesis of max performs the maximum operation along the 3rd axis which is the new axis which dstack has created for us

This will scale to any number of 2D arrays of the same size



回答4:

something like:

numpy_arrays = [A, B, C]

result = [max(elem) for elem in zip(*numpy_arrays)]

?