首页 > 解决方案 > 用于模式 2 位到 2 位的 Python 正则表达式,例如 - 26 到 40

问题描述

请帮忙,正则表达式让我大吃一惊。

我正在清理 Pandas 数据框(python 3)中的数据。

我尝试了很多在网上找到的数字正则表达式组合,但没有一个适合我的情况。我似乎无法弄清楚如何为模式 2 位空间到 2 位空间(例如 26 到 40)编写自己的正则表达式。

我的挑战是从熊猫列 BLOOM(抓取数据)中提取花瓣数量。花瓣经常被指定为“dd to dd花瓣”。我知道正则表达式中的 2 位数字是\d\d或者\d{2}但是我如何将拆分合并为“到”?最好有一个条件,即图案后面跟着单词“petals”。

当然,我不是第一个在 python 中需要正则表达式来获取模式 \d\d​​ 到 \d\d​​ 的人。

编辑:

我意识到没有示例数据框的问题有点令人困惑。所以这是一个示例数据框。

import pandas as pd 
import re

# initialize list of lists 
data = [['Evert van Dijk', 'Carmine-pink, salmon-pink streaks, stripes, flecks.  Warm pink, clear carmine pink, rose pink shaded salmon.  Mild fragrance.  Large, very double, in small clusters, high-centered bloom form.  Blooms in flushes throughout the season.'],
    ['Every Good Gift', 'Red.  Flowers velvety red.  Moderate fragrance.  Average diameter 4".  Medium-large, full (26-40 petals), borne mostly solitary bloom form.  Blooms in flushes throughout the season.'], 
    ['Evghenya', 'Orange-pink.  75 petals.  Large, very double bloom form.  Blooms in flushes throughout the season.'], 
    ['Evita', 'White or white blend.  None to mild fragrance.  35 petals.  Large, full (26-40 petals), high-centered bloom form.  Blooms in flushes throughout the season.'],
    ['Evrathin', 'Light pink. [Deep pink.]  Outer petals white. Expand rarely.  Mild fragrance.  35 to 40 petals.  Average diameter 2.5".  Medium, double (17-25 petals), full (26-40 petals), cluster-flowered, in small clusters bloom form.  Prolific, once-blooming spring or summer.  Glandular sepals, leafy sepals, long sepals buds.'],
    ['Evita 2', 'White, blush shading.  Mild, wild rose fragrance.  20 to 25 petals.  Average diameter 1.25".  Small, very double, cluster-flowered bloom form.  Blooms in flushes throughout the season.']]

# Create the pandas DataFrame 
df = pd.DataFrame(data, columns = ['NAME', 'BLOOM']) 

# print dataframe. 
df 

标签: python-3.xregexdata-cleaningdata-wrangling

解决方案


您可以使用

df['res_col'] = df['src_col'].str.extract(r'(?<!\d)(\d{2}\s+to\s+\d{2})\s*petal', expand=False)

查看正则表达式演示

细节

  • (?<!\d)- 一个消极的向后看,确保当前位置的左边没有数字
  • (\d{2}\s+to\s+\d{2})- 第1组(实际回报str.extract):
    • \d{2}- 两位数
    • \s+to\s+- 1+ 个空格,to字符串,1+ 个空格
    • \d{2}- 两位数
  • \s*petal- 0+ 个空格,后跟petal.

推荐阅读