You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

使用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 _t at 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_keyversion_nrID
LIT1-1.10_t110
LIT1-1.20_t120
LIT1-1.30_t130
LIT4-1.99_t199
LIT4-1.88_t188
LIT4-1.77_t177

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

火山引擎 最新活动