Reputation: 1
import numpy as np
G1 = np.array([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]],)
G1_Compare = G1 > 4
print(G1[G1_Compare])
Output:
[ 5 6 7 8 9 10 11]
I do understand what this does, but I just don't understand what is the operation happening in here.
What is exactly happening behind the scenes?
Also, why doesn't it print the false elements?
Upvotes: 0
Views: 46
Reputation: 3722
Conceptual understanding of G1 > 4
:
G1
is a shape (3,4)
numpy
array.
In G1 > 4
, G1
is participating as an operand in a comparison operation (>
).
The other operand is 4
, which is not an array at all, and has no dimensions.
Now, Broadcasting occurs.
Due to broadcasting, conceptually, the scalar 4
is broadcast into a shape (3,4)
array consisting of just several 4
s as its elements.
So, now, conceptually speaking, the comparison operation >
occurs element-wise between two similarly shaped arrays, each of shape (3,4)
.
This results in a boolean array (G1_Compare
), of shape (3,4)
, consisting of True
and False
values. The True
value occurs at those element-coordinates where the corresponding element of G1
is greater than that of the broadcasted array consisting of 4
s.
Note that broadcasting of array does not actually create any new array (even temporarily) with the broadcasted shape. It is only a concept or metaphor to explain/understand the defined behavior and the result. Internally, numpy
uses index manipulations to achieve the effect of broadcasting, without actually creating any new arrays in the broadcasted shape.
Conceptual understanding of G1[G1_Compare]
:
Here, boolean indexing occurs.
Your question "why doesn't it print the false elements?" doesn't really make sense -- what would be the point of using a boolean index if it were to select the True
-position elements as well as the False
-position elements? The whole point of using a boolean index is to select and return the elements in the True
positions, and exclude the elements in the False
positions.
Upvotes: 1