Julia与numpy的where函数等效吗? [英] What is Julia equivalent of numpy's where function?

查看:113
本文介绍了Julia与numpy的where函数等效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中,numpy中的where根据给定条件选择数组中的元素.

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])

朱莉娅呢? 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆