如何有条件地替换 pandas 数据框列中的子字符串? [英] 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 on the opposite, if there is a '-' character, I want to replace it with a '+'
我显然不能在没有条件的情况下简单地使用replace(),或者最后,所有+ &- 将转换为单个 + 字符.
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,
最佳,
皮埃尔
推荐答案
您可以将正则表达式与接收匹配对象的 lambda 函数一起使用:
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
这篇关于如何有条件地替换 pandas 数据框列中的子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!