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

Python Pandas:基于列中Top x%值为行分配Score值

问题与解决方案

问题描述

给定已按Number of Purchases降序排序的模拟DataFrame:

CustomerID   Number of Purchases

   ABC                5
   DEF               24
   GHI               85
   JKL                2
   MNO              100

需要新增Score列,按以下规则赋值:

  • 前60%的客户:Score = 3
  • 接下来20%的客户:Score = 2
  • 最后20%的客户:Score = 1

以下是适合大型DataFrame的高效实现方法:

方法一:利用pd.qcut分箱赋值

qcut是pandas专门用于按分位数划分数据的函数,属于向量运算,处理大型数据效率极高:

import pandas as pd

# 假设DataFrame已排序,名为df
df = pd.DataFrame({
    'CustomerID': ['ABC', 'DEF', 'GHI', 'JKL', 'MNO'],
    'Number of Purchases': [5, 24, 85, 2, 100]
}).sort_values('Number of Purchases', ascending=False)

# 基于索引分箱(因已排序,索引顺序对应客户排名)
df['Score'] = pd.qcut(
    x=df.index,
    q=[0, 0.6, 0.8, 1.0],  # 划分60%、80%、100%三个分界点
    labels=[3, 2, 1]        # 对应区间的Score值
)

若DataFrame索引非连续整数,可先执行df = df.reset_index(drop=True)重置索引,确保分箱准确。

方法二:手动计算分界点,条件赋值

通过计算总行数的分位数位置,用np.where批量赋值,逻辑直观且边界处理灵活:

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'CustomerID': ['ABC', 'DEF', 'GHI', 'JKL', 'MNO'],
    'Number of Purchases': [5, 24, 85, 2, 100]
}).sort_values('Number of Purchases', ascending=False)

total = len(df)
cut_60 = int(total * 0.6)
cut_80 = int(total * 0.8)

# 嵌套条件赋值
df['Score'] = np.where(
    df.index < cut_60, 3,
    np.where(df.index < cut_80, 2, 1)
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 13:01:19