带有 numpy 数组的条件循环

我试图用 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.])

感谢您的帮助!


ITMISS
浏览 1306回答 3
3回答

慕村225694

在文档中查找np.where:注意:当仅提供条件时,该函数是 的简写 np.asarray(condition).nonzero()。直接使用nonzero应该是首选,因为它对于子类的行为是正确的。本文档的其余部分仅涵盖提供所有三个参数的情况。由于您不提供x和y参数,where因此行为类似于nonzero。 nonzero返回 a tupleof np.arrays,转换为 bool 后为 true。所以你的代码最终评估为:if True:     x = 2*t相反,您想使用:x = np.where((t >= 0) & (t < 3), 2*t, 4*t)

慕仙森

的用法np.where不同dt = 1.0t = 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.]

幕布斯6054654

在您的代码中,if 语句不是必需的,并且会导致问题。np.where() 创建条件,因此您不需要 if 语句。这是您的代码的工作示例,其中包含您想要的输出dt = 1.0t = np.arange(0.0, 5.0, dt)x = np.empty_like(t)np.where((t >=0) & (t < 3),2*t,4*t)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python