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

如何在df中提取特定字符前后子串并生成新列

Pandas DataFrame: Extract Substrings Before/After a Specific Character

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_colafter_charbefore_char
a John/SmithSmitha John
b Jane/DoeDoeb Jane
c Bob/JohnsonJohnsonc 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:10:10