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

Python DataFrame apply调用多列条件函数时TypeError参数报错解决

解决DataFrame apply调用自定义函数的参数错误问题

错误原因

你触发的TypeError: mar_status() got multiple values for argument 'col1',本质是apply的传参逻辑和函数定义不匹配:当使用axis=1调用apply时,它会自动把整行数据作为第一个参数传给函数,如果你额外通过args或其他方式传递参数,就会导致同一个参数被多次赋值,引发冲突。

解决方案

下面提供几种可行的修复方式,按需选择:

方式1:修改函数接收行对象

把函数改成接收整行数据,从行中提取所需列的值,适配apply的传参逻辑:

def mar_status(row):
    rel = row['insured_relationship']
    sex = row['insured_sex']
    hour = row['incident_hour_of_the_day']
    
    # 这里写你的原逻辑,示例:
    if rel in ['wife', 'husband']:
        return 'Married'
    elif rel == 'own_child':
        return 'Child'
    elif rel == 'unmarried':
        return 'Unmarried'
    else:
        return 'Other'

# 调用生成新列
df['marital_status'] = df.apply(mar_status, axis=1)

方式2:用lambda包装函数(不修改原函数)

如果不想改动原函数,用lambda把行中的列值逐个传给函数:

# 假设你的原函数定义如下:
def mar_status(rel, sex, hour):
    # 原逻辑代码
    if rel in ['wife', 'husband']:
        return 'Married'
    elif rel == 'own_child':
        return 'Child'
    elif rel == 'unmarried':
        return 'Unmarried'
    else:
        return 'Other'

# 用lambda包装调用
df['marital_status'] = df.apply(
    lambda row: mar_status(
        row['insured_relationship'],
        row['insured_sex'],
        row['incident_hour_of_the_day']
    ),
    axis=1
)

方式3:用矢量化操作替代apply(推荐)

apply是逐行处理,大数据量下效率较低。可以用numpy.select实现矢量化条件判断,速度更快:

import numpy as np

# 定义条件列表和对应结果
conditions = [
    df['insured_relationship'].isin(['wife', 'husband']),
    df['insured_relationship'] == 'own_child',
    df['insured_relationship'] == 'unmarried'
]
choices = ['Married', 'Child', 'Unmarried']

# 生成新列
df['marital_status'] = np.select(conditions, choices, default='Other')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 16:40:41