【发布时间】: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