numpy如数组中的nan,并将nan替换为平均值

示例代码:

# 如何处理数组中的nan,策略是将nan替换为平均值
 
import numpy as np
t = np.arange(24).reshape(3,8).astype('float') 
t[1,3:] = np.nan    #将第二行三列之后的元素替换为nan
print(t)

# 遍历每一列,然后判断每一列是否有nan
for i in range(t.shape[1]):
    #获取当前列数据
    temp_col = t[:,i]
    # 判断当前列的数据中是否含有nan
    nan_num = np.count_nonzero(temp_col != temp_col) 
    if nan_num != 0: 
        temp_col_not_nan = temp_col[temp_col==temp_col]
        # 将nan替换成这一列的平均值
        temp_col[np.isnan(temp_col)] = np.mean(temp_col_not_nan)

print(t)

猜你喜欢

转载自blog.csdn.net/caoxinjian423/article/details/112121750
NaN