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

如何依据description列值向desc列追加RADIONAVIGATION且不覆盖原有数据

解决方法

你之前的代码错误在于使用了x.replace('', 'RADIONAVIGATION')——空字符串''会匹配字符串中所有字符的间隙(包括首尾和字符之间),导致整个字符串被大量插入目标文本,完全覆盖原有内容。

实现代码

方式1:自定义函数(可读性更高)

import pandas as pd

def update_desc(row):
    # 清理desc的首尾空格,处理空值/NaN情况
    clean_desc = row['desc'].strip() if pd.notna(row['desc']) else ''
    # 判断当前行description是否包含目标字符串
    has_radio_nav = 'RADIONAVIGATION' in row['description']
    
    if has_radio_nav:
        if clean_desc:
            # 已有内容则追加
            return f"{clean_desc} RADIONAVIGATION"
        else:
            # 无内容则直接赋值
            return 'RADIONAVIGATION'
    else:
        # 不包含则返回清理后的原内容
        return clean_desc

# 应用到df
df['desc'] = df.apply(update_desc, axis=1)

方式2:lambda简化版

如果偏好简洁的写法,也可以用一行lambda完成:

df['desc'] = df.apply(lambda row: 
    ('RADIONAVIGATION' if not (row['desc'].strip() if pd.notna(row['desc']) else '') 
     else f"{row['desc'].strip()} RADIONAVIGATION") 
    if 'RADIONAVIGATION' in row['description'] 
    else (row['desc'].strip() if pd.notna(row['desc']) else ''), 
    axis=1
)

效果验证

处理后的数据会符合你的需求:

descriptionremarkdesc
METEOROLOGICAL AIDS 54A['54A']METEOROLOGICAL AIDS
METEOROLOGICAL AIDS 54A RADIONAVIGATION['54A']METEOROLOGICAL AIDS RADIONAVIGATION
RADIONAVIGATIONRADIONAVIGATION

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 21:06:15