nan和inf替换成0
import numpy as np
a = np.array([[np.nan, np.nan, 1, 2], [np.inf, np.inf, 3, 4], [1, 1, 1, 1], [2, 2, 2, 2]])
print (a)
where_are_nan = np.isnan(a)
where_are_inf = np.isinf(a)
#nan替换成0,inf替换成nan
a[where_are_nan] = 0
a[where_are_inf] = 0
print(a)

参考:https://blog.csdn.net/helei001/article/details/53066317
nan值替换成每列的均值
# coding=utf-8
import numpy as np
def fill_ndarray(t1):
for i in range(t1.shape[1]): # 遍历每一列(每一列中的nan替换成该列的均值)
temp_col = t1[:, i] # 当前的一列
nan_num = np.count_nonzero(temp_col != temp_col)
if nan_num != 0: # 不为0,说明当前这一列中有nan
temp_not_nan_col = temp_col[temp_col == temp_col] # 去掉nan的ndarray
# 选中当前为nan的位置,把值赋值为不为nan的均值
temp_col[np.isnan(temp_col)] = temp_not_nan_col.mean() # mean()表示求均值。
return t1
if __name__ == '__main__':
t1 = np.array([[ 0., 1., 2., 3., 4., 5.],
[ 6., 7., np.nan, np.nan, np.nan, np.nan],
[12., 13., 14., 15., 16., 17.],
[18., 19., 20., 21., 22., 23.]])
t1 = fill_ndarray(t1) # 将nan替换成对应的均值
print(t1)
'''
[[ 0. 1. 2. 3. 4. 5.]
[ 6. 7. 12. 13. 14. 15.]
[12. 13. 14. 15. 16. 17.]
[18. 19. 20. 21. 22. 23.]]
'''
参考:https://blog.csdn.net/houyanhua1/article/details/87688990
可惜了这篇博客没有inf替换成均值的方法
inf替换成每列的均值
import numpy as np
a = np.array([[np.nan, np.nan, 1, 2], [np.inf, np.inf, 3, 4], [1, 1, 1, 1], [2, 2, 2, 2]])
print (a)
where_are_nan = np.isnan(a)
where_are_inf = np.isinf(a)
#nan替换成0,inf替换成nan
# a[where_are_nan] = 0
a[where_are_inf] = np.nan
print(a)
##将nan替换成每列的均值
def fill_ndarray(t1):
for i in range(t1.shape[1]): # 遍历每一列(每一列中的nan替换成该列的均值)
temp_col = t1[:, i] # 当前的一列
nan_num = np.count_nonzero(temp_col != temp_col)
if nan_num != 0: # 不为0,说明当前这一列中有nan
temp_not_nan_col = temp_col[temp_col == temp_col] # 去掉nan的ndarray
# 选中当前为nan的位置,把值赋值为不为nan的均值
temp_col[np.isnan(temp_col)] = temp_not_nan_col.mean() # mean()表示求均值。
return t1
data = fill_ndarray(a)
print(data)

我就是缝合大师,哈哈哈
这篇博客介绍了如何在Numpy中处理nan和inf值,提供将nan替换为每列均值以及将inf替换为0的方法。作者分享了参考链接,并幽默地自称为‘缝合大师’。

9707

被折叠的 条评论
为什么被折叠?



