Pandas 字符串提取所有匹配项 [英] Pandas string extract all the matches

查看:86
本文介绍了Pandas 字符串提取所有匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习熊猫系列字符串方法中的正则表达式操作.我能够从字符串中提取第一个数字,但我的正则表达式与第二个数字不匹配.如何捕获这两个数字?

注意第二行,这里的第二个元素是NAN.

代码:

将pandas导入为pddf = pd.DataFrame({'a': ["数字 1.23 有 1.2",数字 12.2 有 12 个"]})pat = r""".+\s+(\d+\.\d+).+((?:\d+\.\d+)?).+"""df['a'].str.extract(pat,flags=re.X,expand=True)

给出:

0 11.2312.2

预期:

0 11.23 1.212.2 南

如何修复正则表达式?

我对正则表达式很陌生,所以请体谅并原谅我的无知.

解决方案

您可以使用 .str.findall\d+\.\d+ 正则表达式:

<预><代码>>>>df['a'].str.findall(r"\d+\.\d+").to_frame()一种0 [1.23, 1.2]1 [12.2]

或者,

<预><代码>>>>pd.DataFrame(df['a'].str.findall(r"\d+\.\d+").tolist())0 10 1.23 1.21 12.2 无

模式匹配

  • \d+ - 1+ 个数字
  • \. - 点
  • \d+ - 1+ 位数字.

请注意,str.findall 不需要使用捕获组来包装整个模式,也可以使用 .str.extractall 的情况在这里.

I am learning regex operation in pandas series string method. I was able to extract the first number from the string, but my regex is not matching the second number. How to capture both the numbers?

Note that second row, the second element is NAN here.

CODE:

import pandas as pd
df = pd.DataFrame({'a': ["number 1.23 has 1.2 ",
                         "number 12.2 has 12 "]})

pat = r""".+\s+
(\d+\.\d+)
.+
((?:\d+\.\d+)?)
.+"""


df['a'].str.extract(pat,flags=re.X,expand=True)

Gives:

0      1
1.23
12.2

Expected:

0    1
1.23 1.2
12.2 NaN

How to fix the regex?

I am very new to regex, so please be considerate and forgive my ignorance.

解决方案

You may use .str.findall with the \d+\.\d+ regex:

>>> df['a'].str.findall(r"\d+\.\d+").to_frame()
             a
0  [1.23, 1.2]
1       [12.2]

Or,

>>> pd.DataFrame(df['a'].str.findall(r"\d+\.\d+").tolist())
      0     1
0  1.23   1.2
1  12.2  None

The pattern matches

  • \d+ - 1+ digits
  • \. - dot
  • \d+ - 1+ digits.

Note that str.findall does not require the whole pattern to be wrapped with a capturing group, as is the case with .str.extractall that could also be used here.

这篇关于Pandas 字符串提取所有匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆