用Pandas数据帧中的列分位数替换异常值

时间:2017-01-20 09:20:30

标签: python pandas dataframe quantile

我有一个数据框:

df = pd.DataFrame(np.random.randint(0,100,size=(5, 2)), columns=list('AB'))
    A   B
0  92  65
1  61  97
2  17  39
3  70  47
4  56   6

以下是5%分位数:

down_quantiles = df.quantile(0.05)
A    24.8
B    12.6

以下是低于分位数的值的掩码:

outliers_low = (df < down_quantiles)
       A      B
0  False  False
1  False  False
2   True  False
3  False  False
4  False   True

我想将df低于分位数的值设置为其列分位数。我可以这样做:

df[outliers_low] = np.nan
df.fillna(down_quantiles, inplace=True)

    A   B
0  92.0  65.0
1  61.0  97.0
2  24.8  39.0
3  70.0  47.0
4  56.0  12.6

但当然应该有更优雅的方式。如果没有fillna,我怎么能这样做? 感谢。

1 个答案:

答案 0 :(得分:9)

您可以使用DF.mask()方法。只要存在True个实例,其他系列的值就会根据匹配的列名进行对齐,并提供axis=1

df.mask(outliers_low, down_quantiles, axis=1)  

enter image description here

另一个变体是在使用波浪号(~)符号反转布尔值掩码后使用DF.where()方法。

df.where(~outliers_low, down_quantiles, axis=1)

enter image description here