使用NumPy数组的条件循环

3

我试图使用numpy数组实现下面这个简单条件语句,但输出结果是错误的。

dt = 1.0
t = np.arange(0.0, 5.0, dt)
x = np.empty_like(t)
if np.where((t >=0) & (t < 3)):
    x = 2*t
else:
    x=4*t

我看到下面的输出结果。
array([0., 2., 4., 6., 8.])

但我期望的是

array([0., 2., 4., 12., 16.])

感谢您的帮助!
3个回答

3
在查找 np.where 的文档时,需要注意:np.where 函数的条件参数(condition)单独使用时,等同于np.asarray(condition).nonzero(), 但应该优先使用 nonzero 函数,因为它可以正确处理子类。本文档仅介绍提供了三个参数的情况。
由于您没有提供 xy 参数,所以 where 的行为类似于 nonzerononzero 返回一个 tuple,其中包含一个或多个 np.arrays,当转换为布尔值时为真。 因此,您的代码最终将被评估为:
if True:
    x = 2*t

相反,你应该使用:

x = np.where((t >= 0) & (t < 3), 2*t, 4*t)

2

在你的代码中,if语句是不必要的,并且导致了问题。

np.where()创建条件,因此您不需要if语句。

这里是您的代码的工作示例和所需的输出

dt = 1.0
t = np.arange(0.0, 5.0, dt)
x = np.empty_like(t)
np.where((t >=0) & (t < 3),2*t,4*t)


如果我有多个if-then条件,因为np.where只允许3个参数,那么编写此代码的最佳方法是什么?dt = 1.0 t = np.arange(0.0, 4.0, dt) x = np.empty_like(t) if ((t>=0.0).any()) & ((t<1.0).any()): x = 2*t elif ((t>=1.0).any()) & ((t<2.0).any()): x = 3*t elif ((t>=2.0).any()) & ((t<3.0).any()): x = 4*t else: x = 5*t - AKSuited
嗨,你只需要像在Excel中一样链接条件。dt = 1.0 t = np.arange(0.0, 5.0, dt) x = np.empty_like(t) x = np.where((t >=0) & (t < 1),2*t,np.where((t >=1) & (t < 2),3*t,np.where((t >=2) & (t < 3),4*t,5*t))) - BP34500

2

np.where 的用法有所不同。

dt = 1.0
t = np.arange(0.0, 5.0, dt)
x = np.empty_like(t)
x = np.where((t >= 0) & (t < 3), 2*t, 4*t)
x

输出

[ 0.,  2.,  4., 12., 16.]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接