What is Julia equivalent of numpy's where function?

£可爱£侵袭症+ 提交于 2021-01-02 06:35:51

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/56137218/what-is-julia-equivalent-of-numpys-where-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!