If you have an array built up out of method chaining, sometimes you need to 
filter it at the very end. This can be annoying because it means you have to 
create a temporary variable just so you can refer to it in the indexing square 
brackets:

_temp = long_and_complicated_expression()
result = _temp[_temp >= 0]

You could also use the walrus operator but this is odd looking and it still 
pollutes the namespace:

result = (_temp := long_and_complicated_expression())[_temp >= 0]

What I would like is to be able to use a lambda inside the indexing square 
brackets, which would take the whole array as an argument and give a boolean 
array:

result = long_and_complicated_expression()[lambda arr: arr >= 0]

I should emphasize, the lambda gets the entire array as its argument, and 
returns an entire mask array of bools. It isn't like the `map` and `filter` 
builtins where it would call the python function once for each element and thus 
be slow.

Pandas already has something similar[1]; you can pass a lambda into `.loc[]` 
that takes a Series and returns a boolean indexer.

[1] 
https://pandas.pydata.org/pandas-docs/version/0.18.1/whatsnew.html#method-chaininng-improvements
_______________________________________________
NumPy-Discussion mailing list -- numpy-discussion@python.org
To unsubscribe send an email to numpy-discussion-le...@python.org
https://mail.python.org/mailman3/lists/numpy-discussion.python.org/
Member address: arch...@mail-archive.com

Reply via email to