4

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
  • 6,381
  • 7
  • 37
  • 70

2 Answers2

13

+ 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,883
  • 4
  • 34
  • 41
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
  • 317,841
  • 20
  • 164
  • 234