如何从熊猫数据框中的列值中删除连续的四位数

时间:2019-01-03 10:51:52

标签: 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                 2
 B         coffee 1                 1
 C        green tea                 4

使用python的最佳方法是什么

1 个答案:

答案 0 :(得分:3)

您需要使用经过仔细应用的正则表达式模式的str.replace

# 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

正则表达式细分
模式(?<!\d)\d{4}(?!\d)将查找恰好4位数字,该数字之前或之后没有数字(因此,少于/多于4位数字的字符串将不予处理)。

(
    ?<!   # negative lookbehind 
    \d    # any single digit
)
\d{4}     # match exactly 4 digits
(
    ?!    # negative lookahead
    \d
)