1

I am new in Python and my question might be too obvious, but I did not find a sufficiently good answer.

Suppose I have a 2D array a=np.array([[1,2,3],[4,5,6],[7,8,9]]). How can I subscribe those elements that satisfy a condition? Suppose, I want to increase by one those elements of a that are greater than 3. In Matlab, I would do it in 1 line: a(a>3)=a(a>3)+1. What about Python? The result should be [[1,2,3],[5,6,7],[8,9,10]].

I am aware that there are functions that can return the indeces I need, like np.where. I am also aware that there is a way of indexing 2D array with two 1D arrays. I was not able to combine those together.

Of course, I am able to do it with for loop. I am interested, is there a convenient Matlab-like way of doing this?

Thanks

Mikhail Genkin
  • 3,247
  • 4
  • 27
  • 47

1 Answers1

4

If you already know how boolean indexing works then just an in-place addition is all you need to do:

In [6]: a=np.array([[1,2,3],[4,5,6],[7,8,9]])

In [7]: a[a>3] += 1  # roughly equal to a = a[a>3] + 1

In [8]: a
Out[8]: 
array([[ 1,  2,  3],
       [ 5,  6,  7],
       [ 8,  9, 10]])
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • 1
    Thanks. The thing that confused me when I tried this, was the immediate output that didn't look like a 2D array. But when I subsequently called `a`, it was displayed correctly – Mikhail Genkin Apr 11 '18 at 20:54
  • 2
    In MATLAB `a(a>4)` displays a column vector; in `numpy` `a[a>4]` is 1d. Because of the (potentially) ragged nature of boolean indexing, it can't return a 2d shape. – hpaulj Apr 11 '18 at 21:06
  • What do you mean by `# roughly equal to a = a[a>3] + 1` ? It is not exactly the same? – Mikhail Genkin Apr 12 '18 at 19:14
  • 1
    @MikhailGenkin Same functionality but in slightly different ways. The in-place version changes the items in-place while the second one creates a new array in the fly and then reassigns it to the array. – Mazdak Apr 12 '18 at 19:19