除以0后,在numpy数组中将NaN替换为0 [英] After division by 0, replace NaN with 0 in numpy arrays

查看:1967
本文介绍了除以0后,在numpy数组中将NaN替换为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在分割两个numpy数组:

I am dividing two numpy arrays:

>>> import numpy as np
>>> a1 = np.array([[ 0,  3],
                   [ 0,  2]])
>>> a2 = np.array([[ 0,  3],
                   [ 0,  1]])
>>> d = a1/a2
>>> d
array([[ nan,   1.],
       [ nan,   2.]])
>>> where_are_NaNs = np.isnan(d)
>>> d[where_are_NaNs] = 0
>>> d
>>> array([[ 0.,  1.],
           [ 0.,  2.]])

我正在寻找一种无需使用for循环即可获得0而不是Nan的方法吗?

I am looking for a way to get 0 instead of Nan without using for loops?

在熊猫中,numpy是否具有与fillna()类似的功能?

Does numpy have a similar function to fillna() in pandas?

推荐答案

下面的方法应该可以将所有NAN转换为0

This below should work and convert all NANs to 0

d[np.isnan(d)] = 0

如果您希望全部都放在同一行,请考虑

If you want it all on one line, consider

d = np.nan_to_num(a1/a2)

将所有NAN转换为0的方法,请参见此处:

Which will convert all NANs to 0, see here: http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.nan_to_num.html

注意:除以0时,应遵循以下@ imp9的解决方案,以避免不必要的警告或错误.

Note: When dividing by 0, you should follow @imp9's solution below to avoid unnecessary warnings or errors.

这篇关于除以0后,在numpy数组中将NaN替换为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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