首页 > 解决方案 > 在 Pandas 中分配 NaN 不粘?

问题描述

我有一个值数据集,它们是 x、y、z 值(经度、纬度、海拔)。nan我想通过公式扫描错误值来替换异常值。一切正常,除非我将值分配给它重置为原始值的数据框。感兴趣的函数是:

def removeOutliers(dataframe, header):  
    for ii in range(len(dataframe['Lng'])):
        dataframe.reset_index(inplace=True, drop=True)
        df_copy = dataframe.copy()
        a = df_copy.iloc[ii]['Lng'] -  df_copy.iloc[:]['Lng']
        b = df_copy.iloc[ii]['Lat'] -  df_copy.iloc[:]['Lat']
        c = np.array((a**2 + b**2)**0.5   )    
        d = np.zeros((len(df_copy['Lng'])))
        e = np.zeros((len(df_copy['Lng'])))
        d[:] = df_copy.iloc[:]['Well']
        e[:] = df_copy.iloc[:][header]
        idx = np.argpartition(c, n_samples+1)
        max_loc = np.where(e[idx[0:n_samples+1]] == e[ii])
        neighbors = np.delete(e[idx[0:n_samples+1]], max_loc)
        avg = np.mean((neighbors))
        std = np.std(neighbors)
        if ii==148:
            print(df_copy.iloc[ii][header])        
        if df_copy.iloc[ii][header] > (avg + tolerance*std) or df_copy.iloc[ii][header] < (avg - tolerance*std):
            df_copy.loc[ii, header] = np.nan
        if ii==148:
            print(df_copy.iloc[ii][header])
            print(avg + tolerance*std)
            print(avg - tolerance*std)
    return df_copy    

new_data = removeOutliers(data_by_zone, 'elevation')

目标是找到最接近的 20 个样本,计算均值和标准差。dev,如果参考样本大于avg+tolerance*std(在这种情况下容差 = 1.5),则替换为 nan。这打印:

5223
nan #this is how I know my if statement is working
372
277

然后我运行 print(new_data.iloc[148]['elevation'])

我得到

5223

所以,就像它正在替换它,但是当我将它分配给 new_data 时,它会重置为原始值。我怎么做nan棒?如果它有所作为,那就是 python3.7 和 pandas0.25.1。注意:我只设置数据框的副本以避免 SettingWithCopy 警告...

更新: 我也尝试过使用df_copy.iloc[ii][header]and df_copy.iloc[ii, df_copy.columns.get_loc(header)] = np.nan,但没有运气

更新 2问题是由 for 循环内的数据框引起的。将其移至循环解决问题之前。

标签: pythonpandas

解决方案


推荐阅读