[英]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?在这种情况下,是否可以使用 np.where() 来获得与
new_amplitude_2
相同的结果作为列表new_amplitude_1
( new_amplitude_1
)?
I read some tutorials online but I can't see the logic to have an if else
inside np.where()
.我在网上阅读了一些教程,但我看不到在
np.where()
有if else
的逻辑。 Maybe I should use another function?也许我应该使用另一个功能?
Here's how you can do it using np.where
:以下是使用
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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.