当数据框中存在大约 1/3 的缺失值时,如何标记所有异常值?

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

假设有一个包含 10000 个样本和 4 个特征的数据框,并且不保证特征是独立的

np.random.seed(42)
data = np.random.randn(10000, 4)
df = pd.DataFrame(data, columns=[f'Feature_{i+1}' for i in range(4)])

missing_rows = np.random.choice(10000, 3000, replace=False)
for row in missing_rows:
    df.iloc[row, np.random.choice(4)] = np.nan

我想找到这个数据框中的所有异常值,我也想在原始数据框中用不同的颜色或字体标记所有这些异常值和那些NA。以下是我的尝试,我正在尝试使用隔离森林,但我不知道该怎么做。任何提示或帮助都会很棒,谢谢

def IQR(series):
    Q1 = series.quantile(0.25)
    Q3 = series.quantile(0.75)
    IQR = Q3 - Q1

    LB = Q1 - 1.5 * IQR
    UB = Q3 + 1.5 * IQR

    return ((series < LB) | (series > UB) | (series.isnull()))

for col in data.columns:
    data[f'abnormal {col}'] = IQR(data[col])
python pandas machine-learning statistics outliers
1个回答
0
投票

使用

applymap

outliers = df.apply(IQR)
def style_outlier(v):
    return outliers.applymap(lambda val: "color:red;" if val else "")

>>> df.style.apply(style_outlier, axis=None)

© www.soinside.com 2019 - 2024. All rights reserved.