如何替换Pandas DataFrame列单元格中的指定子字符串?
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|ABmatches 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:
| BrandName | Specialty |
|---|---|
| A | H |
| B | I |
| A B | J |
| D | K |
| A | L |
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

