簡體   English   中英

從列表理解到 numpy.where()

[英]From list comprehension to numpy.where()

我有以下代碼將嘈雜的方波轉換為無噪聲的方波:

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_2相同的結果作為列表new_amplitude_1new_amplitude_1 )?

我在網上閱讀了一些教程,但我看不到在np.where()if else的邏輯。 也許我應該使用另一個功能?

以下是使用np.where

np.where(amplitude < threshold, low, high)
# array([0, 0, 0, 1, 1, 1, 1, 0, 0, 0])

你可以在沒有位置的情況下做到:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM