01f82f896c
Signed-off-by: David Rotermund <54365609+davrot@users.noreply.github.com> |
||
---|---|---|
.. | ||
README.md |
Where
{:.no_toc}
* TOC {:toc}The goal
Questions to David Rotermund
numpy.where
numpy.where(condition, [x, y, ]/)
Return elements chosen from x or y depending on condition.
condition : array_like, bool Where True, yield x, otherwise yield y.
x, y : array_like Values from which to choose. x, y and condition need to be broadcastable to some shape.
Finding indices
We are using where is this mode:
idx = numpy.where(condition)
2d example
import numpy as np
a = np.arange(0, 15).reshape((5, 3))
print(a)
print()
w = np.where(a > 7)
print(w)
Output:
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]
[12 13 14]]
(array([2, 3, 3, 3, 4, 4, 4]), array([2, 0, 1, 2, 0, 1, 2]))
3d example
import numpy as np
a = np.arange(0, 30).reshape((5, 3, 2))
w = np.where(a > 15)
print(w)
Output:
(array([2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4]), array([2, 2, 0, 0, 1, 1, 2, 2, 0, 0, 1, 1, 2, 2]), array([0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]))
Using the found indices:
import numpy as np
a = np.arange(0, 30).reshape((5, 3, 2))
idx = np.where(a > 15)
a[idx] = 42
print(a)
Output:
[[[ 0 1]
[ 2 3]
[ 4 5]]
[[ 6 7]
[ 8 9]
[10 11]]
[[12 13]
[14 15]
[42 42]]
[[42 42]
[42 42]
[42 42]]
[[42 42]
[42 42]
[42 42]]]
import numpy as np
a = np.arange(0, 30).reshape((5, 3, 2))
a[np.where(a > 15)] = 42
print(a)
Using conditions
numpy.where(condition, x, y)
Identity
In this example nothing happens because independent of the condition the value from a is used:
import numpy as np
a = np.arange(0, 15).reshape((5, 3))
a = np.where(a > 7, a, a)
print(a)
Output:
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]
[12 13 14]]
x is a number
import numpy as np
a = np.arange(0, 15).reshape((5, 3))
a = np.where(a > 7, 42, a)
print(a)
Output:
[[ 0 1 2]
[ 3 4 5]
[ 6 7 42]
[42 42 42]
[42 42 42]]
y is a number
import numpy as np
a = np.arange(0, 15).reshape((5, 3))
a = np.where(a > 7, a, 42)
print(a)
Output:
[[42 42 42]
[42 42 42]
[42 42 8]
[ 9 10 11]
[12 13 14]]
x and y are numbers
import numpy as np
a = np.arange(0, 15).reshape((5, 3))
a = np.where(a > 7, 0, 42)
print(a)
Output:
[[42 42 42]
[42 42 42]
[42 42 0]
[ 0 0 0]
[ 0 0 0]]