Reputation: 1001
I have the following code that converts a noisy square wave to a noiseless one:
import numpy as np
threshold = 0.5
low = 0
high = 1
time = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
amplitude = np.array([0.1, -0.2, 0.2, 1.1, 0.9, 0.8, 0.98, 0.2, 0.1, -0.1])
# using list comprehension
new_amplitude_1 = [low if a<threshold else high for a in amplitude]
print(new_amplitude_1)
# gives: [0, 0, 0, 1, 1, 1, 1, 0, 0, 0]
# using numpy's where
new_amplitude_2 = np.where(amplitude > threshold)
print(new_amplitude_2)
# gives: (array([3, 4, 5, 6]),)
Is is possible to use np.where() in order to obtain identical result for new_amplitude_2
as the list comprehension (new_amplitude_1
) in this case?
I read some tutorials online but I can't see the logic to have an if else
inside np.where()
. Maybe I should use another function?
Upvotes: 1
Views: 309
Reputation: 1320
you can do it without where:
new_ampl2 = (amplitude > 0.5).astype(np.int32)
print(new_ampl2)
Out[11]:
array([0, 0, 0, 1, 1, 1, 1, 0, 0, 0])
Upvotes: 4
Reputation: 88276
Here's how you can do it using np.where
:
np.where(amplitude < threshold, low, high)
# array([0, 0, 0, 1, 1, 1, 1, 0, 0, 0])
Upvotes: 5