Pandas 字符串提取所有匹配项

编程入门 行业动态 更新时间:2024-10-28 14:37:09
本文介绍了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 字符串提取所有匹配项

本文发布于:2023-11-01 17:27:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1549947.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   Pandas

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!