我试图用 numpy 数组实现以下简单条件,但输出是错误的。dt = 1.0t = np.arange(0.0, 5.0, dt)x = np.empty_like(t)if np.where((t >=0) & (t < 3)): x = 2*telse: x=4*t我得到下面的输出array([0., 2., 4., 6., 8.])但我期待着array([0., 2., 4., 12., 16.])感谢您的帮助!
3 回答
![?](http://img1.sycdn.imooc.com/545862aa0001f8da02200220-100-100.jpg)
慕村225694
TA贡献1880条经验 获得超4个赞
在文档中查找np.where
:
注意:当仅提供条件时,该函数是 的简写
np.asarray(condition).nonzero()
。直接使用nonzero
应该是首选,因为它对于子类的行为是正确的。本文档的其余部分仅涵盖提供所有三个参数的情况。
由于您不提供x
和y
参数,where
因此行为类似于nonzero
。 nonzero
返回 a tuple
of np.arrays
,转换为 bool 后为 true。所以你的代码最终评估为:
if True: x = 2*t
相反,您想使用:
x = np.where((t >= 0) & (t < 3), 2*t, 4*t)
![?](http://img1.sycdn.imooc.com/533e4d510001c2ad02000200-100-100.jpg)
慕仙森
TA贡献1827条经验 获得超8个赞
的用法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.]
![?](http://img1.sycdn.imooc.com/5333a1bc00014e8302000200-100-100.jpg)
幕布斯6054654
TA贡献1876条经验 获得超7个赞
在您的代码中,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)
添加回答
举报
0/150
提交
取消