How to replace a sub-string conditionally in a pandas dataframe column?

笑着哭i 提交于 2020-01-24 19:33:26

问题


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


回答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



回答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


来源:https://stackoverflow.com/questions/59508962/how-to-replace-a-sub-string-conditionally-in-a-pandas-dataframe-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!