简体   繁体   中英

Conditional Loop with numpy arrays

I am trying to implement the following simple condition with numpy arrays, but the output is wrong.

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

I get the output below

array([0., 2., 4., 6., 8.])

But I am expecting

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

Thanks for your help!

Looking in the docs for np.where :

Note : When only condition is provided, this function is a shorthand for np.asarray(condition).nonzero() . Using nonzero directly should be preferred, as it behaves correctly for subclasses. The rest of this documentation covers only the case where all three arguments are provided.

Since you don't provide the x and y arguments, where acts like nonzero . nonzero returns a tuple of np.arrays , which is truthy when converted to bool. So your code ends up evaluating as:

if True:
    x = 2*t

Instead, you want to use:

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

The usage of np.where is different

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

Output

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

in your code the if statement is not necessary and causes the problem.

np.where() creates the condition therefore you do not need the if statement.

Here is a working example of your code with the output you want

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM