Python 如何从dataframe中的列值中删除连续四位数字
我有这样一个数据框:Python 如何从dataframe中的列值中删除连续四位数字,python,regex,string,pandas,dataframe,Python,Regex,String,Pandas,Dataframe,我有这样一个数据框: col1 col2 col3 A 12134 tea2014 2 B 2013 coffee 1 1 C green 2015 tea 4 我想删除数字精确出现四次的位置 结果如下所示: col1 col2 col3 A 12134 tea
col1 col2 col3
A 12134 tea2014 2
B 2013 coffee 1 1
C green 2015 tea 4
我想删除数字精确出现四次的位置
结果如下所示:
col1 col2 col3
A 12134 tea 2
B coffee 1 1
C green tea 4
使用python的最佳方法是什么?您需要使用仔细应用的正则表达式模式替换
str:
# Thanks to @WiktorStribiżew for the improvement!
df['col2'] = df['col2'].str.replace(r'(?<!\d)\d{4}(?!\d)', '')
df
col1 col2 col3
0 A 12134 tea 2
1 B coffee 1 1
2 C green tea 4
#感谢@WiktorStribiżew的改进!
df['col2']=df['col2'].str.replace(r'(?这是一个kicka**regex.:O对于breakdown@anky_91哈,如果这让你印象深刻,你应该看看……是的,已经说不出话来了D@coldspeed如果字符串以连续的五位数字开头,那么我想去掉前四位,取第五位。例如,12345abc将被5abcr'(?
(
?<! # negative lookbehind
\d # any single digit
)
\d{4} # match exactly 4 digits
(
?! # negative lookahead
\d
)