用中位数替换离群值时,为什么会出现“ValueError:列的长度必须与键相同”

问题描述 投票:0回答:0

我尝试在数据帧上运行此循环以消除异常值并将其替换为中位数,但我遇到了这个问题:“ValueError:列必须与键长度相同”。 这是我在 DataFrame 上使用的代码:

对于 df2.columns 中的 j:
Q1 = df2[[j]].分位数(q = 0.25)
Q3 = df2[[j]].分位数(q = 0.75)

lower_outliers = Q1 - 1.5*(Q3 - Q1)  
upper_outliers = Q3 + 1.5*(Q3 - Q1)

up_out_count = df2[df2[[j]]>upper_outliers][[j]].count()
lo_out_count = df2[df2[[j]]<lower_outliers][[j]].count()

tot_out_count = up_out_count + lo_out_count
tot_data = df2[[j]].count()
percent = (tot_out_count / tot_data)*100

print(f'Number of outliers in '+ j +' upper: ', up_out_count)
print(f'Number of outliers in '+ j +' lower: ', lo_out_count)
print(f'The percentage of outliers in '+ j +' is: ', percent,'\n\n')

median = df2[[j]].median()
df[[j]] = np.where(df[[j]] > upper_outliers , median, np.where(df2[[j]] < lower_outliers, median, df[[j]]))

我也已经用过这个了,但它也不起作用:

#df[[j]] = np.where(df2[[j]] < lower_outliers, median, df2[[j]])         
#df[[j]] = np.where(df2[[j]] > upper_outliers, median, df2[[j]]) 
#df[[j]] = df[[j]].replace(df2[[j]] < lower_outliers, median)
#df[[j]] = df[[j]].replace(df2[[j]] > upper_outliers, median)

也许要注意,我正在使用双 [[]],因为我一直遇到缩放器与矢量问题。

python-3.x dataframe data-cleaning outliers
© www.soinside.com 2019 - 2024. All rights reserved.