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

如何替换Pandas DataFrame列单元格中的指定子字符串?

Replacing Substrings in a Pandas DataFrame Column

Great question! The original replace() approach works when swapping entire cell values, but since your BrandName column has cells with combined strings (like "ABC B"), we need to target substrings within each cell instead. Here are two simple, effective ways to get your desired output:

Method 1: Use str.replace() with Regular Expressions

Pandas' string methods let you modify parts of a string without affecting the whole cell. We can use a regex pattern to match either "ABC" or "AB" and replace them with "A":

import pandas as pd

# Your sample DataFrame
df = pd.DataFrame({
    'BrandName': ['A', 'B', 'ABC B', 'D', 'AB'],
    'Specialty': ['H', 'I', 'J', 'K', 'L']
})

# Replace substrings
df['BrandName'] = df['BrandName'].str.replace(r'ABC|AB', 'A', regex=True)

How this works:

  • str.replace() operates on each individual string in the column, not just full cell values.
  • The regex ABC|AB matches either "ABC" or "AB" wherever they appear in the string. Longer patterns are prioritized first, so "ABC" gets replaced before "AB" (avoiding issues like turning "ABC" into "AC").
  • Matches are swapped with "A", leaving other content (like the " B" in "ABC B") untouched.

Method 2: Use replace() with regex=True

You can also use the general replace() method with a dictionary of replacements, setting regex=True to treat the keys as substring patterns:

df['BrandName'] = df['BrandName'].replace({'ABC': 'A', 'AB': 'A'}, regex=True)

This achieves the exact same result as Method 1—pick whichever syntax feels more intuitive to you.

Result

After running either method, your DataFrame will look like this:

BrandNameSpecialty
AH
BI
A BJ
DK
AL

Bonus: Target Only Standalone Words

If you want to make sure you're only replacing "ABC" or "AB" when they're standalone words (not part of longer strings like "ABXYZ"), add word boundaries (\b) to your regex:

df['BrandName'] = df['BrandName'].str.replace(r'\bABC\b|\bAB\b', 'A', regex=True)

This prevents accidental replacements in strings where "AB" or "ABC" are part of a larger word.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:13:46