如何在df中提取特定字符前后子串并生成新列
Got it, let's walk through how to handle these two string manipulation tasks in pandas—they're super common, so I'll use your example format to make it concrete.
First, let's set up a sample DataFrame that matches your example input:
import pandas as pd # Sample data matching your "a John/Smith" format df = pd.DataFrame({ "original_col": ["a John/Smith", "b Jane/Doe", "c Bob/Johnson"] })
1. Extract Substring After a Specific Character (New Column)
If you want to pull everything after a specific character (like / in your example) into a new column, you have a few clean options:
- Option 1: Using
str.extract()(most precise for regex control)
This uses a regular expression to capture everything after the target character:# Extract everything after "/" into a new column "after_char" df["after_char"] = df["original_col"].str.extract(r'/(.*)') - Option 2: Using
str.partition()(intuitive for simple splits)partition()splits the string into three parts: before the char, the char itself, and after the char. We just grab the third part:df["after_char"] = df["original_col"].str.partition('/')[2]
2. Extract Substring Up to a Specific Character (New Column)
For grabbing everything up to the target character (stopping right before it), these methods work perfectly:
- Option 1: Using
str.extract()(non-greedy match for first occurrence)
The.*?is a non-greedy match, so it stops at the first instance of your target character:# Extract everything before "/" into a new column "before_char" df["before_char"] = df["original_col"].str.extract(r'(.*?)/') - Option 2: Using
str.partition()(simple and direct)
Grab the first part from the partition result:df["before_char"] = df["original_col"].str.partition('/')[0]
Final Result
After running both operations, your DataFrame will look like this:
| original_col | after_char | before_char |
|---|---|---|
| a John/Smith | Smith | a John |
| b Jane/Doe | Doe | b Jane |
| c Bob/Johnson | Johnson | c Bob |
If your target character isn't /, just replace it with whatever character you need (e.g., @, -, :) in the code above.
内容的提问来源于stack exchange,提问作者Juston Lantrip

