从 pandas 系列(所有组)中提取所有数字字符 [英] Extract all numeric characters from a pandas series (all groups)

查看:59
本文介绍了从 pandas 系列(所有组)中提取所有数字字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Pandas 系列上使用 str.extract('(\d+)') 方法来获取如下所示的电话号码的数字:(123) 456-7890

I am trying to use the str.extract('(\d+)') method on a pandas series to get the digits of a phone number that looks like: (123) 456-7890

使用此方法只返回 123,但我希望输出为 1234567890

Using this method only returns 123 but I want the output to be 1234567890

总的来说,我想知道如何从字符串中获取所有数字而不必担心组.

In general I want to know how to get all digits from a string without having to worry about groups.

谢谢

推荐答案

源代码:

In [66]: x
Out[66]:
              phone
0    (123) 456-7890
1   +321 / 555-7890
2  (111) - 666 7890

在这种情况下,使用 '\D+' RegEx 删除所有非数字要容易得多,因为它可以处理任何类型的电话格式(例如 +123 456789> 或 (123)/456-789 等):

In this case it's much easier to remove all non-digits using '\D+' RegEx as it will take care of any kind of phone format (like +123 456789 or (123) / 456-789, etc.):

In [67]: x['clean'] = x.phone.str.replace(r'\D+', '')

In [68]: x
Out[68]:
              phone       clean
0    (123) 456-7890  1234567890
1   +321 / 555-7890  3215557890
2  (111) - 666 7890  1116667890

使用 Series.str.extract 您需要编写非常复杂的 RegEx 来解析不同的 phone# 格式

Using Series.str.extract you would need to write pretty complicated RegEx's to parse different phone# formats

这篇关于从 pandas 系列(所有组)中提取所有数字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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