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++
1      1234+5678-
dtype: object

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

0    qqq++--www--
1      1234-5678+
dtype: object

Solution 2:

You can do something like this:

Char 1    What-What
Char 2    What+What
Char 3            0
Char 4            0
Char 5            0
Char 6            0
Char 7            0
Char 8            0

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


Char 1    What+What
Char 2    What-What
Char 3            0
Char 4            0
Char 5            0
Char 6            0
Char 7            0
Char 8            0

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

        A  B  C  D  E  F  G          H
Char 1  1  0  0  0  0  0  0  What-What
Char 2  1  0  0  0  0  0  0  What+What
Char 3  0  1  0  0  0  0  0          0
Char 4  0  0  1  0  0  0  0          0
Char 5  0  0  0  1  0  0  0          0
Char 6  0  0  0  0  1  0  0          0
Char 7  0  0  0  0  1  0  0          0
Char 8  0  0  0  0  0  1  0          0

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

        A  B  C  D  E  F  G          H
Char 1  1  0  0  0  0  0  0  What+What
Char 2  1  0  0  0  0  0  0  What-What
Char 3  0  1  0  0  0  0  0          0
Char 4  0  0  1  0  0  0  0          0
Char 5  0  0  0  1  0  0  0          0
Char 6  0  0  0  0  1  0  0          0
Char 7  0  0  0  0  1  0  0          0
Char 8  0  0  0  0  0  1  0          0

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