pandasdataframereplacefindfind-replace

How to find and replace second comma (,) with - in a dataframe using Pandas?


I have dataframe like :

Name Address
Anuj Anuj,Sinha,BB
Sinha Sinha,Anuj BB

In column Adrress, I want to replace all comma (,) except the fist comma in all row with -.

Can anyone please suggest me the possible solution?

provided:

df.dtypes

Customer ID               Int64
First_name-Last_name     string
Address                  string
Phone                    string
Secondary_station        string
Customer_disconnected    string

Solution

  • If there is a maximum of 2 commas, you can use this simple regex:

    df['Address'] = df['Address'].str.replace('(,.*),', r'\1-')
    

    output:

        Name        Address
    0   Anuj  Anuj,Sinha-BB
    1  Sinha  Sinha,Anuj BB
    

    If there are possibly more than 2 commas, you can do:

    df['Address'] = df['Address'].str.split(',').apply(lambda x: x[0]+','+'-'.join(x[1:]))
    

    or, more efficient:

    splits = df['Address'].str.split(',', 1)
    df['Address'] = splits.str[0]+','+splits.str[1].str.replace(',', '-')