[英]Replace a character in a string if it meets a certain condition
I need to filter Phone numbers "where 1 character is equal to 8 and length is equal to 11" and if my condition is True, I want to change 1 character of filtered Phone numbers from '8' to '7'.我需要过滤电话号码“其中 1 个字符等于 8,长度等于 11”,如果我的条件为真,我想将过滤后的电话号码的 1 个字符从“8”更改为“7”。
My code is not working properly...我的代码无法正常工作...
Here is a sample:这是一个示例:
import pandas as pd
df = pd.DataFrame({"Phone" :['+77013655566','87014324366','7014324366','11111','999999','43434343', '8020556612', '+77015452313','7012334212','87010956612', '8012544413', '7777777', '8888888']})
print df
Phone
0 +77013655566
1 87014324366
2 7014324366
3 11111
4 999999
5 43434343
6 8020556612
7 +77015452313
8 7012334212
9 87010956612
10 8012544413
11 7777777
12 8888888
if len(df.loc[df['Phone'].map(str).str.find('8') == 0]) == 11:
df['Phone'].map(str).str.replace('8', '7', n = 1)
else:
#I will write other code
#Expected result:
Phone
0 +77013655566
1 77014324366
2 7014324366
3 11111
4 999999
5 43434343
6 8020556612
7 +77015452313
8 7012334212
9 77010956612
10 8012544413
11 7777777
12 8888888
You can solve it as so你可以这样解决
replacer = lambda x: x.replace('8', '7', 1) if x.startswith('8') and len(x) == 11 else x
df['Phone'] = df['Phone'].apply(replacer)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.