You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于90%分位数检测DataFrame各列异常值并生成描述列

基于90%分位数检测DataFrame异常值并添加描述列

原始数据

首先定义示例DataFrame:

import pandas as pd

df = pd.DataFrame({
    'Customer_ID': range(1, 9),
    'Col 1': [32, 8, 21, 8, 25, 28, 26, 32],
    'Col 2': [1, 3, 4, 22, 25, 42, 1, 33],
    'Col 3': [10, 1, 8, 6, 5, 2, 7, 3]
})

需求说明

基于各列的90%分位数检测异常值(定义大于等于90%分位数的值为异常值),为每一行添加Description列:

  • 无异常值的行标注为-
  • 存在异常值的行标注对应列名,多个异常值用&连接,格式如Col 1 & Col 3 = outliers

实现代码及步骤

  1. 计算目标列的90%分位数
quantiles_90 = df[['Col 1', 'Col 2', 'Col 3']].quantile(0.90)
  1. 标记每行各列是否为异常值
# 生成布尔值矩阵,标记每个值是否达到或超过对应列的90%分位数
outlier_mask = df[['Col 1', 'Col 2', 'Col 3']] >= quantiles_90
  1. 生成每行的描述文本
def get_description(row):
    # 收集当前行中属于异常值的列名
    outlier_cols = row[row].index.tolist()
    if not outlier_cols:
        return '-'
    # 按要求格式拼接文本
    cols_str = ' & '.join(outlier_cols)
    return f'{cols_str} = outliers'

# 按行应用函数,生成Description列
df['Description'] = outlier_mask.apply(get_description, axis=1)
  1. 最终结果
    执行后df的输出如下:
print(df)
#    Customer_ID  Col 1  Col 2  Col 3                Description
# 0            1     32      1     10  Col 1 & Col 3 = outliers
# 1            2      8      3      1                        -
# 2            3     21      4      8                        -
# 3            4      8     22      6                        -
# 4            5     25     25      5                        -
# 5            6     28     42      2         Col 2 = outliers
# 6            7     26      1      7                        -
# 7            8     32     33      3         Col 1 = outliers

代码说明

  • quantile(0.90):计算指定列的90%分位数,返回以列名为索引的Series
  • outlier_mask:利用广播机制,将每列数值与对应分位数对比,生成布尔值矩阵
  • get_description函数:遍历每行布尔值,收集异常列名并按格式拼接;无异常则返回-
  • apply(..., axis=1):按行调用函数,批量生成描述文本列

内容的提问来源于stack exchange,提问作者user19495470

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 12:15:40