【问题标题】:Python Regex for pattern 2 digits to 2 digits like - 26 to 40用于模式 2 位到 2 位的 Python 正则表达式,例如 - 26 到 40
【发布时间】:2020-08-21 07:45:06
【问题描述】:

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

我正在清理 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 

【问题讨论】:

  • df['source_col'].str.extract(r'\b(\d{2}\s+to\s+\d{2})\s*petal', expand=False)?
  • 对,误解了这个问题。

标签: python-3.x regex data-cleaning data-wrangling


【解决方案1】:

这对我有用:

import re

sample = '2 digits (example 26 to 40 petals) and 16 to 43 petals.'
re.compile(r"\d{2}\sto\s\d{2}\spetals").findall(sample)

输出:

['26 to 40 petals', '16 to 43 petals']

正如您所说,\d{2} 找到 2 位数字,\sto\s 找到被空格包围的单词“to”,然后再次 \d{2} 找到第二个 2 位数字,然后是一个空格 (\s) 和单词“花瓣”。

【讨论】:

  • 这在我的情况下不起作用。但感谢正则表达式。在它的帮助下,我能够弄清楚。这篇文章中的所有示例都对我有所帮助。
【解决方案2】:

你可以使用

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

regex demo

详情

  • (?&lt;!\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

【讨论】:

  • 谢谢。我必须稍微修改一下正则表达式才能为我工作,并在提取后添加“.str.strip()”。
【解决方案3】:

发布一个答案来展示我如何解决从 BLOOM 列中提取花瓣数据的问题。我不得不使用多个正则表达式来获取我想要的所有数据。这个问题只涉及我使用的一个正则表达式。

打印后的示例数据框如下所示:

我在遇到导致这篇文章的问题之前创建了这些专栏。我最初的方法是获取括号中的所有数据。

#coping content in column BLOOM inside first brackets into new column PETALS
df['PETALS'] = df['BLOOM'].str.extract('(\\(.*?)\\)', expand=False).str.strip()
df['PETALS'] = df['PETALS'].str.replace("(","") 

# #coping content in column BLOOM inside all brackets into new column ALL_PETALS_BRACKETS
df['ALL_PETALS_BRACKETS'] = df['BLOOM'].str.findall('(\\(.*?)\\)')
df[['NAME','BLOOM','PETALS', 'ALL_PETALS_BRACKETS']]

后来我意识到这种方式只能获取某些行的花瓣值。花瓣可以通过多种方式在 BLOOM 列中指定。另一种常见的模式是“2 位到 2 位”。还有图案“2位数花瓣”。

# solution provided by Wiktor Stribiżew
df['PETALS_Wiktor_S'] = df['BLOOM'].str.extract(r'(?<!\d)(\d{2}\s+to\s+\d{2})\s*petal', expand=False)

# my modification that worked on the main df and not only on the test one. 
# now lets copy part of column BLOOM that matches regex pattern two digits to two digits
df['PETALS5'] = df['BLOOM'].str.extract(r'(\d{2}\s+to\s+\d{2})', expand=False).str.strip()

# also came across cases where pattern is two digits followed by word "petals"
#now lets copy part of column BLOOM that matches regex patern two digits followed by word "petals"
df['PETALS6'] = df['BLOOM'].str.extract(r'(\d{2}\s+petals+\.)', expand=False).str.strip()
df

因为我追求的是“2位数花瓣”模式。我必须修改我的正则表达式,以便它在r'(\d{2}\s+petals+\. 中使用+\. 查找点如果正则表达式写为r'(\d{2}\s+petals.,它会抓取单词花瓣后跟.( 的情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2023-01-18
    相关资源
    最近更新 更多