0

Say I have 4 numpy arrays like:

a : np.random.randn(4,4)

which is like

array([[ 0.8087178 , -1.32970726, -0.62254544,  0.82266235],
   [-0.57101685, -1.39512136, -0.19650182,  0.46574661],
   [-1.06096896,  0.92744505,  1.98807088,  1.11976449],
   [-0.0103123 ,  1.49460442, -0.16151632,  0.96951708]])

then I have b, c, d also equal np.random.randn(4,4)

Now, suppose I want to know the maximum of for each array location in string, like this:

 array([[a, b, d, c],
        [b, c, a, a],
        [c, a, b, b],
        [d, c, a, b]])

How would I do it? lambda function don't seem to work here. I know a loop would work, but is there a batch function that could do this?

More generally, the question would be, how could I apply individual functions to each array element across arrays without using a loop?

Thanks!

1
  • What is 'lambda function'? Commented Aug 7, 2018 at 1:17

2 Answers 2

2

As simple as this:

np.argmax((a,b,c,d),axis=0)

This will give you an array where 0 means a, 1 means b, and so on. If you really care, you can then just apply the map dict(zip(range(4),'abcd')) to it.

For the "more general" question, you are looking at numpy.vectorize.

Sign up to request clarification or add additional context in comments.

1 Comment

np.array(['a','b','c','d'])[np.argmax((a,b,c,d),axis=0)] will return the matrix OP was looking for. +1
0

For your main question: if you stack the arrays together using np.concatenate then you can use np.argmax to get an array that shows which array has the greatest element in each position. The example below shows this for 1D arrays. You'll want axis=2 for 2D arrays.

In [1]: import numpy as np

In [2]: a1 = np.array([1, 2, 3, 4])

In [3]: a2 = np.array([3, 2, 1, 1])

In [4]: a1
Out[4]: array([1, 2, 3, 4])

In [5]: a2
Out[5]: array([3, 2, 1, 1])

In [6]: np.concatenate([a1, a2])
Out[6]: array([1, 2, 3, 4, 3, 2, 1, 1])

In [7]: np.concatenate([[a1], [a2]])
Out[7]: 
array([[1, 2, 3, 4],
       [3, 2, 1, 1]])

In [9]: ai = np.concatenate([[a1], [a2]])

In [11]: np.argmax(ai, axis=1)
Out[11]: array([3, 0])

In [12]: np.argmax(ai, axis=0)
Out[12]: array([1, 0, 0, 0])

Your other question "how could I apply individual functions to each array element across arrays without using a loop?" is unclear. I don't understand what it means but it should probably be a separate question.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.