【问题标题】:How to delete continuous four digits from a column value in pandas dataframe [duplicate]如何从熊猫数据框中的列值中删除连续的四位数字[重复]
【发布时间】:2019-05-29 23:00:40
【问题描述】:

我有一个这样的数据框:

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最好的方法是什么

【问题讨论】:

    标签: python regex string pandas dataframe


    【解决方案1】:

    您将需要 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
    

    正则表达式分解
    模式(?&lt;!\d)\d{4}(?!\d) 将准确查找前面或后面没有数字的 4 位数字(因此留下少于/多于 4 位数字的字符串)。

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

    【讨论】:

    • 那是一些 kicka** 正则表达式。 :O 也为故障+1
    • @anky_91 呵呵,如果这让你印象深刻,你应该看看this...
    • 是的,已经无语了。 :D
    • @coldspeed 如果字符串以连续的五位数字开头,那么我想删除前四位数字并取第五位数字怎么办?例如 12345abc 将替换为 5abc
    • r'((?&lt;=\D)|(?&lt;=^))\d{4}(?=\D|$)' = r'(?&lt;!\d)\d{4}(?!\d)'。这是stackoverflow.com/a/3532970/3832970的骗子
    猜你喜欢
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 2016-11-12
    • 2020-03-23
    • 2016-01-29
    • 2019-01-28
    • 1970-01-01
    • 2019-06-19
    相关资源
    最近更新 更多