3

In my MySQL database, phone in a VARCHAR. Then, I import this to a pandas dataframe. Here's my data:

data5

id   phone
1     +62634783472
2       0834838483
3              +62

What I want is convert +62 to 0, expected output would be like this

id   phone
1       0634783472
2       0834838483
3                0

I already try two thing, there are

data5['phone'] = data5['phone'].str.replace('+62', '0')

data5['phone'] = data5['phone'].replace(to_replace='+62', value='0', regex=True)

And the result is:

error: nothing to repeat at position 0

What is I miss?

Nabih Bawazir
  • 5,275
  • 6
  • 29
  • 53

2 Answers2

8

+ is a special character and you have to escape it with \:

import pandas as pd
data5 = pd.DataFrame({"id": [1, 2, 3], 
                      "phone": ["+62634783472", "0834838483", "+62"]})

data5['phone'] = data5['phone'].str.replace('\+62', '0')

# data5
   id       phone
0   1  0634783472
1   2  0834838483
2   3           0
Foxan Ng
  • 6,468
  • 4
  • 28
  • 39
1

replace and regex=True

data5.replace({'\+62':'0'},regex=True)
Out[76]: 
   id       phone
0   1  0634783472
1   2  0834838483
2   3           0
BENY
  • 296,997
  • 19
  • 147
  • 204