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

前端 未结 3 1386
时光取名叫无心
时光取名叫无心 2020-12-21 19:58

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

相关标签:
3条回答
  • 2020-12-21 20:29
    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
    
    0 讨论(0)
  • 2020-12-21 20:31

    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)
    
    0 讨论(0)
  • 2020-12-21 20:36

    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

    0 讨论(0)
提交回复
热议问题