我有以下代码,可以将有噪声的方波转换为无噪声的方波:
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]),)是否可以使用np.where()来获得与本例中的列表理解(new_amplitude_1)相同的new_amplitude_2结果?
我在网上读了一些教程,但我看不出在np.where()中使用if else的逻辑。也许我应该使用另一个函数?
发布于 2020-01-14 16:35:33
下面是如何使用np.where完成此操作
np.where(amplitude < threshold, low, high)
# array([0, 0, 0, 1, 1, 1, 1, 0, 0, 0])发布于 2020-01-14 16:47:33
您可以在没有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])https://stackoverflow.com/questions/59730036
复制相似问题