如何采取下限和上限来消除异常值

Gav*_*vin 4 python pandas

如何计算 99% 和 1% 百分位数作为每列的上限和下限,如果值 >= 99% 百分位数,则将该值重新定义为 99% 百分位数的值;类似地,如果 value <= 1% 百分位数,则将 value 重新定义为 1% 百分位数的值

np.random.seed(2)
df = pd.DataFrame({'value1': np.random.randn(100), 'value2': np.random.randn(100)})
df['lrnval'] = np.where(np.random.random(df.shape[0])>=0.7, 'learning', 'validation')
Run Code Online (Sandbox Code Playgroud)

如果我们有数百列,我们可以使用 apply 函数代替 do 循环吗?

lle*_*iou 7

根据 Abdou 的回答,以下内容可能会节省您一些时间:

for col in df.columns:
    percentiles = df[col].quantile([0.01, 0.99]).values
    df[col][df[col] <= percentiles[0]] = percentiles[0]
    df[col][df[col] >= percentiles[1]] = percentiles[1]
Run Code Online (Sandbox Code Playgroud)

或使用numpy.clip

import numpy as np
for col in df.columns:
    percentiles = df[col].quantile([0.01, 0.99]).values
    df[col] = np.clip(df[col], percentiles[0], percentiles[1])
Run Code Online (Sandbox Code Playgroud)