3

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!

3 Answers 3

3

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)
2

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.]
2

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)

2
  • What is the best way to write this code if I have multiple if-then conditions since np.where only allows 3 arguments? 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
    Commented Sep 21, 2020 at 17:25
  • Hi, you just need to chain the condition, like in 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
    Commented Sep 22, 2020 at 12:43

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.