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

基于字符串长度的条件替换:仅移除7位英国邮编的空格

解决方案

当然可以结合长度判断实现这个需求,不过要注意你原代码里的df和df1大概率是笔误,应该统一指向同一个DataFrame。以下是两种直接可行的实现方式:

方式一:用numpy.where做条件替换

import numpy as np

# 统一使用正确的DataFrame变量,这里假设为df
df['Client Postcode'] = np.where(
    df['Client Postcode'].str.len() == 7,  # 判断原含空格的邮编长度是否为7
    df['Client Postcode'].str.replace(" ", ""),  # 符合条件则移除空格
    df['Client Postcode']  # 不符合则保留原内容
)

方式二:用apply自定义处理逻辑

def process_postcode(postcode):
    if len(postcode) == 7:
        return postcode.replace(" ", "")
    return postcode

df['Client Postcode'] = df['Client Postcode'].apply(process_postcode)

针对你给出的示例数据测试:

  • 第一行邮编CF1 1DA长度为7,处理后变为CF11DA
  • 第二行邮编CF951AF长度为6,会保持原内容不变

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 23:33:30