Skip to content Skip to sidebar Skip to footer

How To Replace A Sub-string Conditionally In A Pandas Dataframe Column?

I have a Series of strings (timestamps) and I would like to conditionally replace sub-string inside these strings: - if there is a '+' character, I want to replace it with '-' - or

Solution 1:

You can use regex with lambda function that receives the match object:

0    qqq--++www++
11234+5678-
dtype: object

s.str.replace(pat=r"\+|-", repl= lambda mo: "+"if mo.group()=="-"else"-", regex=True)

0    qqq++--www--
11234-5678+
dtype: object

Solution 2:

You can do something like this:

Char 1    What-What
Char 2    What+What
Char 30
Char 40
Char 50
Char 60
Char 70
Char 80

mySeries.loc[mySeries.str.contains(r'[-+]') == True] = mySeries.str.translate(str.maketrans("+-", "-+")) 


Char 1    What+What
Char 2    What-What
Char 30
Char 40
Char 50
Char 60
Char 70
Char 80

If it's not a series you have to do it this way:

        A  B  C  D  E  F  G          H
Char 11000000  What-What
Char 21000000  What+What
Char 301000000
Char 400100000
Char 500010000
Char 600001000
Char 700001000
Char 800000100

df.H.loc[a.str.contains(r'[-+]') == True] = df.H.str.translate(str.maketrans("+-", "-+"))   

        A  B  C  D  E  F  G          H
Char 11000000  What+What
Char 21000000  What-What
Char 301000000
Char 400100000
Char 500010000
Char 600001000
Char 700001000
Char 800000100

Post a Comment for "How To Replace A Sub-string Conditionally In A Pandas Dataframe Column?"