如何在Pandas中提取DataFrame列中两个特定字符间的子字符串?
Hey there! Let's break down how to solve your exact problem first, then cover the general approach for pulling substrings between two specific characters in Pandas.
1. Solution for Your Wage Column Case
Your Wage column has values like €123K, and you need to extract the numeric part to create a Wage2 column. The cleanest, most reliable way to do this is with Pandas' str.extract() paired with a regular expression:
import pandas as pd # Example DataFrame to test with data = {'Wage': ['€123K', '€45K', '€6789K', '€10K']} df = pd.DataFrame(data) # Extract the numeric part between € and K df['Wage2'] = df['Wage'].str.extract(r'€(\d+)K') # Optional: Convert to numeric type for calculations df['Wage2'] = pd.to_numeric(df['Wage2']) print(df)
This will output:
Wage Wage2 0 €123K 123 1 €45K 45 2 €6789K 6789 3 €10K 10
Here's how the regex €(\d+)K works:
€matches the euro symbol exactly(\d+)is a capturing group that grabs one or more digits (this is the value we want to extract)Kmatches the trailing "K" exactly
2. General Method for Extracting Substrings Between Two Characters
When you need to pull content between any pair of delimiters (not just € and K), here are the most common approaches:
Option 1: Regular Expressions (Most Flexible)
Use str.extract() with a regex pattern that targets your left and right delimiters, with a capturing group for the content in between.
- For any character type (letters, numbers, symbols) between delimiters:
The# Example: Extract text between '(' and ')' df['new_col'] = df['original_col'].str.extract(r'\((.*?)\)').*?is a non-greedy match, so it stops at the first occurrence of the right delimiter. - For only numeric characters:
# Replace LEFT/RIGHT with your actual delimiters df['new_col'] = df['original_col'].str.extract(r'LEFT_DELIMITER(\d+)RIGHT_DELIMITER')
Option 2: Chained str.split() (Simple Fixed Delimiters)
If your delimiters are fixed and don't appear elsewhere in the string, you can split the string twice:
# For your wage example, this also works: df['Wage2'] = df['Wage'].str.split('€').str[1].str.split('K').str[0]
This splits first at €, takes the second part of the split, then splits that at K and takes the first part. It's less flexible than regex but great for straightforward cases.
Option 3: str.slice() (Fixed Delimiter Positions)
If your delimiters are always in the same position (e.g., € is always the first character, K is always the last), you can slice directly:
# For '€123K' (length 4), slice from index 1 to -1 (skip first and last character) df['Wage2'] = df['Wage'].str[1:-1]
This is the fastest method but only works if delimiter positions are consistent across all rows.
内容的提问来源于stack exchange,提问作者Moreno

