Join result of findall using comma

Viewed 48

I'm trying to obtain all phone numbers from a column into a separate column.Multiple phone numbers should be comma separated. Code I'm using is attached. When I add .str.join(','), the result is coming as Blank. Without it, I get data in a list format.

phone_regex=[r'(\D\(\d{3}\).\d{3}.\d{4})',r'(\D\(\d{3}\)\d{3}.\d{4})']
sep_pattern = r"|".join(phone_regex)
df['Phone'] = df['Location'].str.findall(sep_pattern).str.join(',')

Eg: 2434 abc eerq
pretoria, yosoi 61611
(309) 839-1330 & (234)232-1377

Expected output -> Phone column : (309) 839-1330,(234)232-1377

1 Answers

Please try below solution, it might help you.

import pandas as pd

data = {
  "calories": [420, 380, 390],
  "phone": ['(309) 839-1330 & (234)232-1377test', '(309) 839-1331' , '(309) 839-1330 & (234)232-1377 & (309) 839-1331']
}

df = pd.DataFrame(data)

print(df) 
phone_regex=r'(\(\d{3}\).*\d{3}.*\d{4})'
df['Phone_upd'] =df['phone'].str.extract(phone_regex,expand=True)
df['Phone_upd'] =df['Phone_upd'].str.split('&').str.join(",")

print(df)

output:

  calories                                            phone
0       420               (309) 839-1330 & (234)232-1377test
1       380                                   (309) 839-1331
2       390  (309) 839-1330 & (234)232-1377 & (309) 839-1331

   calories  ...                                        Phone_upd
0       420  ...                   (309) 839-1330 , (234)232-1377
1       380  ...                                   (309) 839-1331
2       390  ...  (309) 839-1330 , (234)232-1377 , (309) 839-1331

[3 rows x 3 columns]
Related