3 ms·
Great article full of examples, learned quite a bit new things. Personally I don't quite get why something like a[a > 5] = 0 is possible (a is NumPy array).
by metalrain 6y ago
Great article full of examples, learned quite a bit new things.
Personally I don't quite get why something like
a[a > 5] = 0
is possible (a is NumPy array).
I think it is confusing to use same name for element wise comparison and the array itself. Are comparison operators overloaded to generate this kind of predicate function or view in other contexts as well or is this some sort of special case that is handled by indexing (__getitem__ call)?
- Schiphol 6y agoa > 5 results in a boolean array, via 'broadcasting'. These are rules that allow numpy to interpret the 5 as an array with the same dimensions as a, but full of 5s.
- niklasbuschmann 6y agoIt’s the array accessing that is overloaded. a > 5 is a boolean array with the same dimension as a, and now the overloaded method for array access gets called with this boolean array. I also found it incredibly confusing the first time I saw this, but like all the numpy magic based on overloading, it’s confusing the first time you see it, but incredibly handy afterwards.
- metalrain 6y agoThat kind of makes sense. You use logical expressions to build mask that you use to generate view in the outer expression.
- fantod 6y agoBoth are overloaded (__gt__ and __getitem__). My question to you is: How would expect this to be written (in Python)?
- metalrain 6y agoI guess lambda is too verbose a[lambda i: i > 5] = 0 Probably would expect something like this np.set(a, lambda i: i > 5, 0) But that might be too cumbersome when combining values from multiple arrays.
- fantod 6y agoYou made me realize, I think of the brackets as saying "where". vec[2] is vec where the index is 2. vec[vec > 5] is vec where the entries of vec are greater than 5, etc.
- beagle3 6y agoK makes this explicit with the ‘where’ function which converts a Boolean array into the list of indices of true values. Thus, x[4 5 6] is index access (“at”); also x@4 5 6 x[&x>3] is “x at where x is greater than 3” ; can also be written x@&x>3