我正在学习熊猫系列字符串方法中的正则表达式操作.我能够从字符串中提取第一个数字,但我的正则表达式与第二个数字不匹配.如何捕获这两个数字?
注意第二行,这里的第二个元素是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.2Expected:
0 1 1.23 1.2 12.2 NaNHow 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 NoneThe 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 字符串提取所有匹配项
发布评论