Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

python - Set numpy array elements to zero if they are above a specific threshold

Say, I have a numpy array consists of 10 elements, for example:

a = np.array([2, 23, 15, 7, 9, 11, 17, 19, 5, 3])

Now I want to efficiently set all a values higher than 10 to 0, so I'll get:

[2, 0, 0, 7, 9, 0, 0, 0, 5, 3]

Because I currently use a for loop, which is very slow:

# Zero values below "threshold value".
def flat_values(sig, tv):
    """
    :param sig: signal.
    :param tv: threshold value.
    :return:
    """
    for i in np.arange(np.size(sig)):
        if sig[i] < tv:
            sig[i] = 0
    return sig

How can I achieve that in the most efficient way, having in mind big arrays of, say, 10^6 elements?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
In [7]: a = np.array([2, 23, 15, 7, 9, 11, 17, 19, 5, 3])

In [8]: a[a > 10] = 0

In [9]: a
Out[9]: array([2, 0, 0, 7, 9, 0, 0, 0, 5, 3])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...