首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >向量化包含条件语句的代码

向量化包含条件语句的代码
EN

Stack Overflow用户
提问于 2021-08-31 07:04:43
回答 1查看 59关注 0票数 2

我一直在为一个脚本使用for循环,我认为for循环会使脚本运行得太慢。我认为我可以通过矢量化提高速度,但我在弄清楚如何将我的代码矢量化时遇到了一些麻烦。我正在复制一些简单的示例代码,它们或多或少地模仿了我试图在实际代码中实现的内容,以使问题更容易理解。(抱歉,如果它不是最优雅的或技术上的声音。我还在不断获得使用Python的经验。)

代码语言:javascript
运行
复制
import numpy as np

def create_combo(input1,input2):

    combo = input1 + input2
    return combo

def another_combo(monitor,scalar_1,scalar_2):

    add_more = monitor + scalar_1 + scalar_2

    return add_more

# Initialize monitor
monitor = 0

# Initialize a threshold variable
threshold = 15

# Create input arrays
primary_1 = [1, 3, 5, 7, 9]
primary_2 = [2, 4, 6, 8, 10]

primary_1 = np.array(primary_1)
primary_2 = np.array(primary_2)

storage_vec = []
for i in range(5):
    # Create input variables
    scalar_1 = 0.5
    scalar_2 = 2

    # Call the create_combo function 
    combination = create_combo(primary_1[i],primary_2[i])

    # call the another_combo function
    add_on = another_combo(monitor,scalar_1,scalar_2)

    monitor = combination + add_on

    # Check if monitor exceeds threshold
    if monitor > threshold:
        # Store the index if so
        storage_vec.append(i)
        # Reset the variable, monitor
        monitor = 0

我可以理解将名为create_combo的函数向量化是多么容易。我还可以看到,将名为monitor的变量设为向量也很简单。

我遇到的麻烦是如何在向量中的特定点重置monitor变量,并在重置后继续使用monitor进行计算。因此,我一直使用monitor作为标量,并对函数输入的每个元素进行计算。然而,这似乎太慢了,我知道矢量化通常会加快速度。

我读到np.where()函数可能会有所帮助,但我也不确定如何在这种情况下应用它。

有什么建议吗?

EN

回答 1

Stack Overflow用户

发布于 2021-08-31 09:16:37

你的例子可能过于复杂(或者你的例子不完整)。

但是,如果我们想轻松地创建storage_vec,我们可以注意到,监视器在每一步之后增加21.5,直到它达到阈值。

因此,向量storage_vec可以简单地用以下命令计算:

代码语言:javascript
运行
复制
#Increase value:
inc = primary_1[-1]+primary_2[-1]+scalar_1+scalar_2 # = 21.5 
#floor division
fd = threshold//inc
#ceil division
cd = -(-threshold//inc)
#storage_vec 
storage_vec = np.r_[fd:10:cd]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68994226

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档