使用np.linspace如何实现多值函数?

问题描述 投票:0回答:1

我有一个多值函数,我想将其与 np.linspace 结合使用。每当函数中有 if/else 条件时,我都会收到值错误。

我预计将函数 f 应用于 np.linspace 类似于映射,如以下 MWE 所示:

def f(n):
    if n < 3 or n > 5:
        return 0
    else:
        return n

a = list(range(0, 11))
print(a)
print(list(map(f, a)))

b = np.linspace(0, 10, 11)
print(b)
print(f(b))

这对于常规列表工作正常,但对于 np.linspace 则失败并出现错误

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

看来我错了, np.linspace 出于某种原因想要检查数组的每个元素是否满足条件。我不想使用any() 或all(),因为那不是我想要做的。最好的方法是什么?

python numpy scientific-computing
1个回答
0
投票

您需要使用口罩,例如:

b = np.linspace(0, 10, 11)
mask = np.logical_or(b < 3, b > 5)
b[mask] = 0
© www.soinside.com 2019 - 2024. All rights reserved.