gpt4 book ai didi

python - 如何使用正则表达式从字符串中提取前两个字符

转载 作者:太空狗 更新时间:2023-10-30 01:27:16 26 4
gpt4 key购买 nike

引用:Pandas DataFrame: remove unwanted parts from strings in a column

引用上面链接中提供的答案。我研究了一些正则表达式,并计划深入研究,但与此同时我需要一些帮助。

我的数据框是这样的:

df:

  c_contofficeID
0 0109
1 0109
2 3434
3 123434
4 1255N9
5 0109
6 123434
7 55N9
8 5599
9 0109

伪代码

如果前两个字符是 12,则将其删除。或者,将 12 添加到前两个字符中没有 12 的字符。

结果如下:

  c_contofficeID
0 0109
1 0109
2 3434
3 3434
4 55N9
5 0109
6 3434
7 55N9
8 5599
9 0109

我使用上面链接中的答案作为起点:

df['contofficeID'].replace(regex=True,inplace=True,to_replace=r'\D',value=r'')

我试过以下方法:

尝试 1)

df['contofficeID'].replace(regex=True,inplace=True,to_replace=r'[1][2]',value=r'')

尝试 2)

df['contofficeID'].replace(regex=True,inplace=True,to_replace=r'$[1][2]',value=r'')

尝试 3)

df['contofficeID'].replace(regex=True,inplace=True,to_replace=r'?[1]?[2]',value=r'')

最佳答案

新答案
来自@Addison 的评论

# '12(?=.{4}$)' makes sure we have a 12 followed by exactly 4 something elses
df.c_contofficeID.str.replace('^12(?=.{4}$)', '')

如果 ID 必须有四个字符,则更简单

df.c_contofficeID.str[-4:]

旧答案
使用 str.replace

df.c_contofficeID.str.replace('^12', '').to_frame()

enter image description here

关于python - 如何使用正则表达式从字符串中提取前两个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40273313/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com