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

如何拆分pandas字符串列取等号后半部分,解决空值导致的报错问题

需求说明

想要将字符串按等号拆分后提取第二部分,单字符串测试代码如下:

a = "https://imagesvc.meredithcorp.io/v3/mm/image?url=https%3A%2F%2Fimages.media-allrecipes.com%2Fuserphotos%2F4418848.jpg"
output = re.split("=", a)[1]
print(output)

输出结果为:https%3A%2F%2Fimages.media-allrecipes.com%2Fuserphotos%2F4418848.jpg

报错情况

需要将该逻辑应用到pandas DataFrame的整列上,尝试了两种写法都出现报错,且该列存在空值,不确定是否会对输出造成影响。
第一种写法:

mexican['Image'] = mexican['Image'].str.split("=")[1]

报错信息:

ValueError: Length of values (1) does not match length of index (2982)

第二种写法:

for i in mexican['Image']:
  mexican["Image"] = re.split("=", i)[1]

报错信息:

IndexError: list index out of range

解决方案

问题原因是列中存在Nan值,使用try-except方法处理该场景,代码如下:

for i in range(len(data['Image'])):
    try:
        data['Image'][i]=(data['Image'][i].split('='))[1]
    except:
        pass

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 21:06:01