1

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 on the opposite, if there is a '-' character, I want to replace it with a '+'

I obviously cannot use simply replace() without condition, or in the end, all + & - will be converted to a single + character.

mySeries = mySeries.str.replace('+','-', regex=False)
mySeries = mySeries.str.replace('-','+', regex=False)

Please, how should I operate this sign inversion?

I thank you in advance for your help. Have a good day,

Bests,

Pierre

pierre_j
  • 895
  • 2
  • 11
  • 26
  • You could try to use a temporary character to swap the initial `+` into that character, then swap the `-` to `+` then swap the temp character to `-`. More importantly, why do you need to do this? – sshashank124 Dec 28 '19 at 07:38

2 Answers2

1

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
oppressionslayer
  • 6,942
  • 2
  • 7
  • 24
  • Hi, thanks a lot for your answer. Please, would you say .loc is a vectorized method? (just out of curiosity) Thanks again, this is of great help! – pierre_j Dec 28 '19 at 19:59
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
kantal
  • 2,331
  • 2
  • 8
  • 15
  • Hello Kantal, thanks for your help. I am not so familiar with regex, albeit I am aware it does have real power/flexibility. I am trying the option above. Thanks nonetheless, I really appreciate! Bests, – pierre_j Dec 28 '19 at 20:01