Eric Bal
Eric Bal

Reputation: 1185

Array Expressions in Numpy

Pls. NumPy Only:

import numpy as np
A = np.ones((5,5))*3
print A

[[ 3.  3.  3.  3.  3.]
 [ 3.  3.  3.  3.  3.]
 [ 3.  3.  3.  3.  3.]
 [ 3.  3.  3.  3.  3.]
 [ 3.  3.  3.  3.  3.]]

B = np.ones((5,5))*5
print B
[[ 5.  5.  5.  5.  5.]
 [ 5.  5.  5.  5.  5.]
 [ 5.  5.  5.  5.  5.]
 [ 5.  5.  5.  5.  5.]
 [ 5.  5.  5.  5.  5.]]


C = np.ones((5,5))
C[0:2,0:2] = 99
print C

[[ 99.  99.   1.   1.   1.]
 [ 99.  99.   1.   1.   1.]
 [  1.   1.   1.   1.   1.]
 [  1.   1.   1.   1.   1.]
 [  1.   1.   1.   1.   1.]]

A, B, and C are the given conditions. I want to calculate the maximum between A, B where the C values are 99; and put the results into A. The following code works correctly.

A[C==99] = np.max([A, B],axis=0)[C==99]

print A

The expected result is:

[[ 5.  5.  3.  3.  3.]
 [ 5.  5.  3.  3.  3.]
 [ 3.  3.  3.  3.  3.]
 [ 3.  3.  3.  3.  3.]
 [ 3.  3.  3.  3.  3.]]

However, I am wondering if there is better way of solving it. I mean more simplier, faster, or easier way...

Upvotes: 1

Views: 133

Answers (2)

ali_m
ali_m

Reputation: 74222

You could convert Divakar's solution to a one-liner using np.where:

np.where((C == 99) & (B > A), B, A)

The syntax is:

np.where(<mask>, <value_if_mask>, <value_if_not_mask>)

Upvotes: 2

Divakar
Divakar

Reputation: 221614

You can use boolean indexing here and thus avoid calling np.max like so -

mask = (B>A) & (C==99)
A[mask] = B[mask]

Basically, we insert values into A only where values in B are greater than those in A thus replicating the maxcriteria and then overlap that with the condition of C being 99 with C==99. This gives us a boolean array or mask as listed in the first line of code. Then, we use this mask to map A and B and transfer masked values from B to A in the second line of code.


Here's a sample run (notice the value changes at the end in A as compared to the values in A at the start) -

In [66]: A
Out[66]: 
array([[2, 2, 4, 6, 2, 3],
       [6, 4, 2, 4, 3, 5],
       [5, 4, 4, 3, 6, 4],
       [4, 2, 4, 5, 6, 5],
       [2, 5, 5, 5, 2, 5]])

In [67]: B
Out[67]: 
array([[5, 4, 6, 4, 5, 3],
       [5, 6, 3, 4, 7, 6],
       [7, 3, 5, 3, 7, 5],
       [7, 3, 6, 4, 6, 7],
       [7, 4, 7, 7, 3, 6]])

In [68]: C
Out[68]: 
array([[100,  99, 100, 100,  99, 100],
       [100,  99,  99, 100, 100, 100],
       [ 99,  99, 100,  99, 100, 100],
       [100, 100, 100, 100, 100, 100],
       [100,  99,  99, 100,  99,  99]])

In [69]: mask = (B>A) & (C==99)

In [70]: A[mask] = B[mask]

In [71]: A
Out[71]: 
array([[2, 4, 4, 6, 5, 3],
       [6, 6, 3, 4, 3, 5],
       [7, 4, 4, 3, 6, 4],
       [4, 2, 4, 5, 6, 5],
       [2, 5, 7, 5, 3, 6]])

Upvotes: 1

Related Questions