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

Python:如何基于DataFrame行内其他值新增列(自定义函数实现)

问题解决:新增hemisphere列时的ValueError错误

错误原因

你代码的核心问题是调用apply时传参逻辑错误:

  • 使用apply(axis=1)时,Pandas会把每行数据作为单个Series传入函数,但你通过args=(species_custom['continent'],)把整个continent列的Series传给了函数的y参数。
  • 函数里执行y in northern时,实际是在判断整个Series是否属于northern列表,这在Pandas中会触发歧义错误(因为无法确定你要判断所有元素还是任意元素满足条件)。

修正方案

方案1:直接对continent列应用自定义函数(推荐,效率更高)

先简化自定义函数,让它接收单个大洲字符串参数:

northern = ['North America', 'Asia', 'Europe']
southern = ['Africa','South America', 'Oceania']

def get_hemisphere(continent):
    if continent in northern:
        return 'northern'
    elif continent in southern:
        return 'southern'
    else:
        return 'Not Found'

然后直接对continent列调用apply:

species_custom['hemisphere'] = species_custom['continent'].apply(get_hemisphere)

方案2:保留axis=1的逐行处理(适合需要用到多列的场景)

如果后续需要用到行内其他列数据,可以调整函数接收整行数据,再提取大洲值:

northern = ['North America', 'Asia', 'Europe']
southern = ['Africa','South America', 'Oceania']

def get_hemisphere(row):
    continent = row['continent']
    if continent in northern:
        return 'northern'
    elif continent in southern:
        return 'southern'
    else:
        return 'Not Found'

调用时无需额外传参,直接指定axis=1:

species_custom['hemisphere'] = species_custom.apply(get_hemisphere, axis=1)

验证结果

运行修正后的代码,你的DataFrame会新增hemisphere列,结果如下:

countrycodecontinentplantsinvertebratesvertebratestotalhemisphere
AfghanistanAFGAsia523340northern
AlbaniaALBEurope57161137northern
AlgeriaDZAAfrica244081145southern

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 12:48:24