在pandas中使用regex从多个括号中提取字符串

2024-10-04 11:30:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从一个数组中的多个括号中提取多个字符串,并创建新的列

以下字符串位于df的一列中:

Unfurnished 1 Bdrm 1st flr Flat. Hall. Lounge. Kitch. Bdrm. Shower rm (CT band - A). Deposit & references required. No pets. No smokers. Rent £500 p.m Entry by arr. Viewing Owner 07425 163047 or contact solicitors. Landlord reg: 305350/110/22531. (EPC band - C).

我一直试图在两个新列中提取CT波段和EPC波段数据(每组信息各一列)。我尝试了多个版本的代码,还尝试使用来自https://regex101.com/r/5XjNqh/1的信息

例:下面的代码

properties['Council_tax']=properties.Description.str.extract('(\(CT[^()*&?%])',expand=False)

返回

(CT

预期产出:

| Description        | Council_tax_band | EPC_band |
|--------------------|------------------|----------|
| Above string       |        A         |     C    | 
| Example string 2   |        B         |     F    |
| Example string 3   |        C         |     D    |

同时,单词“Band”也被发现为“Band”

我不相信我在这里能很好地正确使用正则表达式。有什么想法吗


Tags: no字符串代码信息bandstringexample波段
1条回答
网友
1楼 · 发布于 2024-10-04 11:30:21

你可以用

df['Council_tab_band'] = df['Description'].str.extract(r'(?i)\(CT\s+band\s*-\s*([^()]+)\)', expand=False)
df['EPC_band'] = df['Description'].str.extract(r'(?i)\(EPC\s+band\s*-\s*([^()]+)\)', expand=False)

regex demo #1regex demo #2

正则表达式详细信息

  • (?i)-不区分大小写的修饰符
  • \(-a(字符
  • EPC-一个字符串
  • \s+-1+空格
  • band-一个单词{}
  • \s*-\s*-用空格括起来的连字符
  • ([^()]+)-组1:除()以外的任何1个或多个字符
  • \)-a)字符

相关问题 更多 >