使用pd.Series.str.extractall与re.findall提取Pandas DataFrame列中数字
Extract version_nr and ID from Primary_key in Pandas
To split the Primary_key string into version_nr and ID, you can use Pandas' str.extract() method with a regular expression that captures the relevant numeric parts. Here's how to do it step by step:
Step 1: Understand the pattern
Each Primary_key follows the format [Prefix]-[version_nr].[ID]_t. We need to capture the number after the hyphen (before the dot) as version_nr, and the number between the dot and underscore as ID.
Step 2: Use regex to extract the values
The regex pattern r'^.*-(\d+)\.(\d+)_t$' will:
^.*-: Match everything up to and including the hyphen(\d+): Capture the first numeric group (version_nr)\.: Match the dot separator(\d+): Capture the second numeric group (ID)_t$: Match the trailing_tat the end of the string
Step 3: Implement the code
import pandas as pd # Your sample DataFrame df = pd.DataFrame({ 'Primary_key': [ 'LIT1-1.10_t', 'LIT1-1.20_t', 'LIT1-1.30_t', 'LIT4-1.99_t', 'LIT4-1.88_t', 'LIT4-1.77_t' ] }) # Extract the two columns df[['version_nr', 'ID']] = df['Primary_key'].str.extract(r'^.*-(\d+)\.(\d+)_t$') # Convert to integer type (optional but useful for numeric operations) df[['version_nr', 'ID']] = df[['version_nr', 'ID']].astype(int) print(df)
Output:
| Primary_key | version_nr | ID |
|---|---|---|
| LIT1-1.10_t | 1 | 10 |
| LIT1-1.20_t | 1 | 20 |
| LIT1-1.30_t | 1 | 30 |
| LIT4-1.99_t | 1 | 99 |
| LIT4-1.88_t | 1 | 88 |
| LIT4-1.77_t | 1 | 77 |
This approach is efficient and works reliably for the given pattern. If your Primary_key format varies slightly, you can adjust the regex pattern to match those variations.
内容的提问来源于stack exchange,提问作者stomar02




