在python中,where
在 numpy 中根据给定条件选择数组中的元素。
>>> 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])
在 Julia 呢?
filter
将用作选择元素,但如果 if
它将丢弃其他元素未使用表达式。但是,我不想使用 if
.我需要为
filter
编写更复杂的函数吗? (没有 if
)或任何其他选择?编辑 :我找到了解决方案,但如果有人对此有更好的想法,请回答这个问题。
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
最佳答案
有几种方式,最明显的就是广播ifelse
像这样:
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
您也可以使用
@.
宏,以确保您得到正确的点:@. ifelse(a < 5, a, 10a)
或使用理解
[ifelse(x<5, x, 10x) for x in a]
您当然也可以使用循环。
关于julia - Julia 相当于 numpy 的 where 函数是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56137218/