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

如何基于Pandas DataFrame条件调整count字段数值

如何根据用户行为类型和访问次数调整Pandas DataFrame的count字段?

看起来你需要根据用户的行为类型(购买/浏览)和浏览次数重新计算count字段的值,我给你两种实用的实现方案:

方案一:自定义函数 + apply(灵活易维护)

这种方式适合规则较多、后续可能需要调整的场景,逻辑清晰好修改:

首先明确规则映射:

  • 当type为orderline(购买行为):直接设为1.0
  • 当type为access(浏览行为):
    • 浏览次数≥20 → 0.9
    • 浏览次数=15 → 0.8
    • 浏览次数=10 → 0.5
    • 浏览次数=4 → 0.2
    • 其他浏览次数可按需设置默认值(比如按次数/20比例计算,或固定低数值)

代码实现:

import pandas as pd

# 假设原始数据已加载到df中
# 定义浏览次数到count值的映射字典
access_count_mapping = {
    4: 0.2,
    10: 0.5,
    15: 0.8
}

def get_count_value(row):
    if row['type'] == 'orderline':
        return 1.0
    elif row['type'] == 'access':
        # 优先处理20次及以上的高频浏览
        if row['number'] >= 20:
            return 0.9
        # 从映射字典取对应值,无匹配则按次数/20计算比例(也可改成固定默认值)
        return access_count_mapping.get(row['number'], row['number'] / 20)
    # 未知行为类型默认设为0
    return 0.0

# 应用函数更新count字段
df['count'] = df.apply(get_count_value, axis=1)

方案二:numpy.where链式判断(性能更优)

如果你的数据集很大,用numpy的向量化操作速度会更快,适合简单的条件链场景:

import pandas as pd
import numpy as np

df['count'] = np.where(
    df['type'] == 'orderline',
    1.0,
    np.where(
        df['number'] >= 20,
        0.9,
        np.where(
            df['number'] == 15,
            0.8,
            np.where(
                df['number'] == 10,
                0.5,
                np.where(
                    df['number'] == 4,
                    0.2,
                    # 其他浏览次数按比例计算,非access类型设为0
                    df['number'] / 20 if df['type'] == 'access' else 0.0
                )
            )
        )
    )
)

两种方案都能实现你要的效果:比如原始数据中第0行(number=4,access类型)会变成0.2,第1行(number=10,access类型)变成0.5,所有购买行为的行都设为1.0,完全符合你的预期输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 10:32:34