Python双输入客户分群函数apply调用报TypeError问题排查
自定义用户分群列开发报错问题
原始提问
我需要为数据表创建新列,计算逻辑依赖两个字段:last_purchase_in_days、order_count。
编写的代码如下:
def segmentor(last_purchase_in_days,order_count): if (customer_df['last_purchase_in_days'] <= 30) & (customer_df['order_count']>=4): return 'best', elif (customer_df['last_purchase_in_days'] <=180) & (customer_df['order_count']>=4): return 'loyal', elif (customer_df['last_purchase_in_days'] <=30) & (customer_df['order_count']==1): return 'recent', elif (customer_df['last_purchase_in_days'] <=180) & (customer_df['order_count']==1): return 'defecting', elif (customer_df['last_purchase_in_days'] <=180) & (customer_df['order_count']<=3): return 'promising', elif (customer_df['last_purchase_in_days'] <=360): return 'at_risk', elif (customer_df['last_purchase_in_days'] >=360): return 'dormant', else: return '???' customer_df['segment']=customer_df.apply(lambda x: segmentor(x)
运行时报错:TypeError: segmentor() missing 1 required positional argument: 'order_count'
注:我没有把最后一个判断分支改成直接返回'dormant'的else逻辑,目的是排查是否存在遗漏的判断条件。
已核实字段类型:
customer_df.dtypes last_purchase_in_days int64 order_count int64
问题根因与修复方案
- 报错直接触发原因:函数定义要求接收
last_purchase_in_days、order_count两个必填入参,但apply的lambda调用逻辑只把整行对象x作为单个参数传入函数,没有拆解取出两个字段的实际值,因此触发缺失order_count入参的报错。 - 函数内部逻辑漏洞:即便修正传参后可以运行,当前函数内部并未使用传入的两个参数值,反而直接引用全局
customer_df的整列数据做判断,这种写法会将整列的布尔结果传入分支判断,既不符合逐行计算的逻辑,还会触发维度不匹配的错误。另外return 'best',末尾多写了逗号,会把返回值变为元组类型,不是预期的字符串结果。 - 逐行apply的必加参数:使用apply逐行计算时必须指定
axis=1,否则会默认按列遍历,传入的x是列对象而非行数据,依然会触发参数错误。另外原代码中apply调用的语句末尾缺失闭合括号,语法上就不完整,也会触发语法解析错误。
修正后可运行的代码
def segmentor(last_purchase_in_days, order_count): # 直接使用传入的单条记录参数值做判断 if (last_purchase_in_days <= 30) & (order_count >= 4): return 'best' elif (last_purchase_in_days <= 180) & (order_count >= 4): return 'loyal' elif (last_purchase_in_days <= 30) & (order_count == 1): return 'recent' elif (last_purchase_in_days <= 180) & (order_count == 1): return 'defecting' elif (last_purchase_in_days <= 180) & (order_count <= 3): return 'promising' elif (last_purchase_in_days <= 360): return 'at_risk' elif (last_purchase_in_days >= 360): return 'dormant' else: return '???' # 逐行调用时,明确传入两个字段的实际值,指定按行遍历 customer_df['segment'] = customer_df.apply( lambda x: segmentor(x['last_purchase_in_days'], x['order_count']), axis=1 )
补充说明
- 保留的
???兜底逻辑可正常标记所有未匹配判断规则的异常数据,方便排查遗漏的分群条件,不影响核心逻辑运行。 - 若处理的数据量较大,逐行apply的运行效率较低,可替换为
np.select的向量化计算逻辑,运行速度可提升数十倍。
内容的提问来源于stack exchange,提问作者Luc
相关产品推荐
相关产品推荐

