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列,结果如下:
| country | code | continent | plants | invertebrates | vertebrates | total | hemisphere |
|---|---|---|---|---|---|---|---|
| Afghanistan | AFG | Asia | 5 | 2 | 33 | 40 | northern |
| Albania | ALB | Europe | 5 | 71 | 61 | 137 | northern |
| Algeria | DZA | Africa | 24 | 40 | 81 | 145 | southern |
内容的提问来源于stack exchange,提问作者Jas
相关产品推荐
相关产品推荐

