简体   繁体   中英

From list comprehension to numpy.where()

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?

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

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

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