In python, where
in numpy choose elements in array based on given condition.
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.where(a < 5, a, 10*a)
array([ 0, 1, 2, 3, 4, 50, 60, 70, 80, 90])
What about in Julia? filter
would be used as selecting elements but it drops other elements if if
expression not being used. However, I don't want to use if
.
Do I need to write more sophisticated function for filter
(without if
) or any other alternatives?
EDIT: I found the solution, but if anyone has better idea for this, please answer to this question.
julia > a = collect(1:10)
10-element Array{Int64,1}:
1
2
3
4
5
6
7
8
9
10
julia> cond = a .< 5
10-element BitArray{1}:
true
true
true
true
false
false
false
false
false
false
julia> Int.(cond) .* a + Int.(.!cond) .* (10 .* a)
10-element Array{Int64,1}:
1
2
3
4
50
60
70
80
90
100
There are several ways, the most obvious is broadcasting ifelse
like this:
julia> a = 0:9 # don't use collect
0:9
julia> ifelse.(a .< 5, a, 10 .* a)
10-element Array{Int64,1}:
0
1
2
3
4
50
60
70
80
90
You can also use the @.
macro in order to make sure that you get the dots right:
@. ifelse(a < 5, a, 10a)
or use a comprehension
[ifelse(x<5, x, 10x) for x in a]
You can of course use a loop as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With