julia - Julia 相当于 numpy 的 where 函数是什么?

标签 julia

在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/

相关文章:

random - Julia,生成四个 1 :3, 之间的 Int8 整数数组,我需要一个包吗?

Julia:图遍历的正确数据结构是什么?

macros - 为什么这个 Julia 宏_不_需要 `esc` ?

julia - 使用可选的位置参数定义 Julia 函数

julia - 如何在不使用 eval 的情况下从符号中获取函数?

vector - 如何从包含 Julia 范围的向量中获取值

package - Pkg.clone 过时了吗?

python - Julia 的 `@edit` 宏的 Python 等价物是什么?

struct - Julia 抛出 : too few type parameters specified in "new{...}"

julia - 在 Julia DataFrame 中查找一行