如何替换大于几个值的Python NumPy Array的所有元素? [英] How to replace all elements of Python NumPy Array that are greater than a several values?

查看:166
本文介绍了如何替换大于几个值的Python NumPy Array的所有元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以替换Python NumPy Array中大于某个值的所有元素:

I know that I can replace all elements of Python NumPy Array that are greater than some value:

np.putmask(A, A>0.5, 5)

其中A>0.5是阈值,5是新的替代值.但是,如何在更多条件下使用它?例如:

Where A>0.5 is the threshold and 5 the new replacement. However, how can I do it for more conditions? for example for:

if x.all <0:
    return 00.1
elif x.all >0:
    return 1

其中x是一个数组.我试图:

Where x is an array. I tried to:

np.putmask(x, x<0, 00.1)

np.putmask(x, x>0, 1)

但是,我想一行完成.知道如何使用putmask或任何其他方法在一行中进行这种类型的替换吗?

However, I would like to do it in a single line. Any idea of how to do this type of replacements in just a single line with putmask or any other method?

推荐答案

您是否正在寻找对偶np.where,即

Are you looking for dual np.where i.e

A = np.array([0,1,2,3,1,-5,-6,-7])

k = np.where(A>0,1,np.where(A<0,0.01,A))

或者您可以将np.select用于多个条件.

Or you can use np.select for multiple conditions .

k = np.select([A>0,A<0],[1,.01],A)

输出:

[ 0.    1.    1.    1.    1.    0.01  0.01  0.01]

这篇关于如何替换大于几个值的Python NumPy Array的所有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆