pandas对序列应用函数,检查前n个字符是否与预定义的字符串值匹配,如果匹配,则需要更新现有值 &



我正在尝试将一个函数应用于熊猫系列,该系列检查前3个字符以及值的前2个字符。

如果它们匹配,前3或2个字符(取决于匹配的是哪一个)需要用'0'替换,其余字符保持不变。

原来的dtype是'O'类型,我已经尝试将其转换为'string'类型,但仍然无法使其工作。

示例数据如下:

012xxxxxxx
+27xxxxxxxx
011xxxxxxx
27xxxxxxxx
etc...

我正在评估的条件是如果前3个字符=='+27'替换'+27'with'0'或者如果前两个字符=='27'替换'27'with'0'

我有下面的apply method但是值没有被更新。

def normalize_number(num):

if num[:3] == '+27':
# num.str.replace(num[:3], '0') ## First Method
return '0' + num[4:] ## Second Method
else:
return num

if num[:2] == '27':
# num.str.replace(num[:2], '0') 
return '0' + num[3:] 
else:
return num
df['number'].apply(normalize_number)

我在这里错过了什么?

看起来你应该在这里使用正则表达式。字符串以27开头,前面有一个可选的+,替换为0:

df['number2'] = df['number'].str.replace('^+?27', '0', regex=True)

输出:

number     number2
0   012xxxxxxx  012xxxxxxx
1  +27xxxxxxxx   0xxxxxxxx
2   011xxxxxxx  011xxxxxxx
3   27xxxxxxxx   0xxxxxxxx
为什么你的方法失败

你的方法失败了,因为你太早返回了一个else语句。你应该使用:

def normalize_number(num):
if num[:3] == '+27':
return '0' + num[4:] ## Second Method
elif num[:2] == '27':
return '0' + num[3:] 
else:
return num

NB。使用上面的regex方法,它会更有效

正则表达式

^      # match start of string
+     # match literal +
?      # make previous match (the "+") optional
27     # match literal 27

regex演示

相关内容

最新更新