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

如何在DataFrame中提取客户首末次有效访问渠道(排除首尾Direct)

解决方案:按客户聚合首/末渠道(跳过前置/后置Direct)

核心思路

优先用Pandas的分组聚合能力实现,比嵌套For循环效率高得多;嵌套循环逻辑可行但仅适合极小数据量场景。

推荐实现步骤

  1. 按客户ID和访问日期排序
    确保每个客户的访问记录按时间先后排列,这是计算首/末渠道的前提:

    df = df.sort_values(['Customer ID', 'Date'])
    
  2. 定义首/末渠道计算函数

    • 首渠道:遍历客户渠道列表,跳过所有前置Direct,返回第一个非Direct渠道;若全为Direct则返回Direct
    • 末渠道:倒序遍历客户渠道列表,跳过后置Direct,返回最后一个非Direct渠道;若全为Direct则返回Direct
    def get_first_non_direct(channels):
        for chan in channels:
            if chan != 'Direct':
                return chan
        return 'Direct'
    
    def get_last_non_direct(channels):
        for chan in reversed(channels):
            if chan != 'Direct':
                return chan
        return 'Direct'
    
  3. 分组聚合生成结果
    按Customer ID分组,应用上述函数聚合渠道列:

    result = df.groupby('Customer ID')['Channel'].agg(
        first_channel=get_first_non_direct,
        last_channel=get_last_non_direct
    ).reset_index()
    

嵌套For循环的可行性说明

嵌套For循环确实能实现需求,但性能极差,仅适合数据量极小的情况,步骤如下:

  • 提取所有唯一的Customer ID
  • 遍历每个ID,筛选该客户的所有渠道记录并按日期排序
  • 手动遍历渠道列表找首渠道,倒序遍历找末渠道
  • 将结果存入新DataFrame

这种方法在数据量较大时会明显卡顿,远不如Pandas内置分组聚合高效。

示例验证

用示例输入测试:

# 示例输入数据
data = {
    'Customer ID': ['A', 'A', 'A', 'B', 'B', 'C'],
    'Date': ['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-01', '2023-01-02', '2023-01-01'],
    'Channel': ['Direct', 'Google', 'Direct', 'Direct', 'Direct', 'Facebook']
}
df = pd.DataFrame(data)

运行后得到预期输出:

Customer IDfirst_channellast_channel
AGoogleGoogle
BDirectDirect
CFacebookFacebook

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 06:42:34