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 r
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
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)
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