Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Julia equivalent of numpy's where function?

Tags:

julia

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
like image 484
Jongsu Liam Kim Avatar asked May 14 '19 19:05

Jongsu Liam Kim


1 Answers

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.

like image 86
DNF Avatar answered Sep 30 '22 19:09

DNF