python:在numpy中合并屏蔽 [英] python: Combined masking in numpy

查看:82
本文介绍了python:在numpy中合并屏蔽的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个numpy数组中,我想将所有naninf替换为一个固定的数字.我可以一步来节省计算时间(数组很大)吗?

In a numpy array I want to replace all nan and inf into a fixed number. Can I do that in one step to save computation time (arrays are really big)?

a = np.arange(10.0)
a[3] = np.nan
a[5] = np.inf
a[7] = -np.inf
# a: [  0.   1.   2.  nan   4.  inf   6. -inf   8.   9.]

a[np.isnan(a)] = -999
a[np.isinf(a)] = -999
# a: [  0.   1.   2.  -999.   4.  -999.   6. -999.   8.   9.]

上面的代码可以正常工作.但我正在寻找类似的东西:

The code above works fine. But I am looking for something like:

a[np.isnan(a) or np.isinf(a)] = -999

哪个不起作用,我可以明白为什么.只是认为如果只检查一次a的每个项目可能会更好.

Which does not work and I can see why. Just thinking it might be better if every item of a is only checked once.

推荐答案

这似乎可行:

a[np.isnan(a) | np.isinf(a)] = 2

实际上,

np.isnan()np.isinf()返回两个布尔numpy数组.

np.isnan() and np.isinf() in fact return two boolean numpy arrays.

布尔numpy数组可以与按位运算(例如&和|

boolean numpy arrays can be combined with bitwise operations such as & and |

这篇关于python:在numpy中合并屏蔽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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