除以0后,将numpy数组中的NaN替换为0
After division by 0, replace NaN with 0 in numpy arrays
我正在划分两个 numpy 数组:
>>> 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 的方法?
numpy在pandas中是否有类似fillna()
的功能?
下面的这个应该有效并将所有 NAN 转换为 0
d[np.isnan(d)] = 0
如果您希望所有内容都在一条线上,请考虑
d = np.nan_to_num(a1/a2)
这会将所有 NAN 转换为 0,请参阅此处:http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.nan_to_num.html
注意:除以0时,您应该按照@imp9下面的解决方案来避免不必要的警告或错误。
您可能应该在 np.errstate(divide='ignore', invalid='ignore')
的上下文中进行除法,这样除以 0 就不会引发错误或警告,无论股息本身是否为零(这两个是单独的警告)。
with np.errstate(divide='ignore', invalid='ignore'):
d = a1/a2
#Geotob's solution
d[np.isnan(d)] = 0
如果您希望它发出警告,请将 'ignore'
更改为 'warn'
。 Reference
我正在划分两个 numpy 数组:
>>> 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 的方法?
numpy在pandas中是否有类似fillna()
的功能?
下面的这个应该有效并将所有 NAN 转换为 0
d[np.isnan(d)] = 0
如果您希望所有内容都在一条线上,请考虑
d = np.nan_to_num(a1/a2)
这会将所有 NAN 转换为 0,请参阅此处:http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.nan_to_num.html
注意:除以0时,您应该按照@imp9下面的解决方案来避免不必要的警告或错误。
您可能应该在 np.errstate(divide='ignore', invalid='ignore')
的上下文中进行除法,这样除以 0 就不会引发错误或警告,无论股息本身是否为零(这两个是单独的警告)。
with np.errstate(divide='ignore', invalid='ignore'):
d = a1/a2
#Geotob's solution
d[np.isnan(d)] = 0
如果您希望它发出警告,请将 'ignore'
更改为 'warn'
。 Reference