Extract all numeric characters from a pandas series (all groups)

こ雲淡風輕ζ 提交于 2019-11-28 11:16:46

问题


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

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.

Thanks


回答1:


Source DF:

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

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

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




回答2:


df = pd.DataFrame({'no': ['(123) 456-7890', '+321 / 555-7890']})
df['clean'] = df.no.str.extractall('(\d+)').unstack().apply(''.join, axis=1)

Result:

    no              clean
0   (123) 456-7890  1234567890
1   +321 / 555-7890 3215557890



回答3:


Or you can also use pandas replace method,

df['clean'] = df['phone'].replace('\D+', '', regex = True)

Or if you want to overwrite the column itself use

df['clean'].replace('\D+', '', regex = True, inplace = True)


来源:https://stackoverflow.com/questions/43876281/extract-all-numeric-characters-from-a-pandas-series-all-groups

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!