什么是 Julia 相当于 numpy 的 where 函数? [英] What is Julia equivalent of numpy's where function?
问题描述
在python中,where
in numpy 根据给定条件选择数组中的元素.
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])
在 Julia 中呢?filter
将用作选择元素,但如果未使用 if
表达式,则会删除其他元素.但是,我不想使用 if
.
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
.
我是否需要为 filter
(不带 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
推荐答案
有几种方式,最明显的就是像这样广播ifelse
:
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)
或使用理解
[ifelse(x<5, x, 10x) for x in a]
你当然也可以使用循环.
You can of course use a loop as well.
这篇关于什么是 Julia 相当于 numpy 的 where 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!