11

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
Jongsu Liam Kim
  • 717
  • 1
  • 7
  • 23

1 Answers1

10

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.

DNF
  • 11,584
  • 1
  • 26
  • 40
  • `ifelse` is what I was looking for. Thanks! – Jongsu Liam Kim May 14 '19 at 21:24
  • 1
    Another way to use the comprehension is with the ternary operator [x<5 ? x : 10x for x in a] . But note that in this case, only one of true or false expressions will be evaluated depending on the result of the condition evaluation in each iteration. This is different from ifelse() where both true and false expressions are always evaluated. – WebDev May 16 '19 at 12:09