Martin
Martin

Reputation: 221

Python Array slicing. [:,:]

I have this code that I am looking over and commenting (I made some improvements to it but I have not really looked in-depth at the math and creation part)

Declaration :

percentile = ((nextImage - BaselineMin) / (BaselineMax - BaselineMin)) * 100

Where nextImage, BaselineMin and BaselineMax are all 720x600 numpy arrays.

Essentially, out of this, I should get another 720x600 Numpy arry

Calling

percentile[:, :][percentile[:, :] == 0] = -999

I am interested to know what each part does. Me and a co-worker looked at it and tried to replicate it with a sample 2x2 and 3x3 array and all we got is []. Alternatively, we got a flattened list, but could not replicate it.

This has to do with array slicing, but i've never seen anything like this. I have taken a look at the other questions around here, but none of them have anything like this.

Upvotes: 0

Views: 853

Answers (3)

forty_two
forty_two

Reputation: 534

That line of code sets every element in "percentile" that has a value of 0 to -999.

Here is a simple 2 by 2 example:

>>> import numpy as np
>>> arr = np.array([[1,2],[0,4]])
>>> arr
array([[1, 2],
       [0, 4]])
>>> arr[:,:][arr[:,:] == 0] = -999
>>> arr
array([[   1,    2],
       [-999,    4]])

As Warren Wessecker mentions, that can be simplified. Consider the following:

>>> arr = np.array([[1,2],[0,4]])
>>> arr
array([[1, 2],
       [0, 4]])
>>> arr[arr == 0] = -999
>>> arr
array([[   1,    2],
       [-999,    4]])

Upvotes: 1

ar-ms
ar-ms

Reputation: 745

Cutting the operation

first part

percentile[:, :] == 0 or just percentile == 0 will give a boolean numpy array of 720x600, True where the value==0 otherwise False.

second part

percentile[percentile == 0] gives the values that meet the condition, so all 0 value in the array.

third and last part

percentile[percentile == 0] = -999, update the zero values by -999.

An example

import numpy as np

A = np.random.rand(4, 4)
A[A >= 0.5] = 1

The samples that are >= to 0.5 will be replaced by 1 in this array of random samples.

Upvotes: 1

Will Molter
Will Molter

Reputation: 530

As I understand it, the line of code in question reads like this:

"Set anything in percentile that is 0 to -999".

The first part percentile[:,:] just refers to every element in percentile. I'm fairly sure you wouldn't need the array slicing here, just replacing with percentile.

The index on percentile, percentile[:,:] == 0 then, should become a matrix of all booleans, True if the corresponding element in percentile is 0 and False otherwise. Again, the array slicing percentile[:,:] is not necessary.

Indexing an array like this is called masking, and the matrix of booleans is called a mask. Essentially the mask selects the items of the indexed array where the mask is True so you can do something with them; here they are being set to -999.

Hope that helps!

Upvotes: 2

Related Questions