【问题标题】:Regex: How to capture words with spaces/hyphens excluding numbers?正则表达式:如何捕获带有空格/连字符的单词,不包括数字?
【发布时间】:2019-03-08 22:55:31
【问题描述】:

我有一个如下所示的数据集:

Column1
-------
abcd - efghi 1234
aasdas - asdas 54321
asda-asd 2344
aasdas(asd) 5234

我希望能够提取所有排除数字的内容,因此它看起来像这样:

Column2
-------
abcd - efghi
aasdas - asdas
asda-asd
aasdas(asd)

这是我当前的正则表达式:

df['Column2'] = df['Column1'].str.extract('([A-Z]\w{0,})', expand=True)

但它只提取排除括号和连字符的第一个单词。任何帮助将不胜感激...谢谢!

【问题讨论】:

    标签: python regex string pandas


    【解决方案1】:

    喜欢使用replace

    df.Column1.str.replace('\d+','')
    Out[775]: 
    0      abcd-efghi 
    1    aasdas-asdas 
    2        asda-asd 
    3     aasdas(asd) 
    Name: Column1, dtype: object
    #df.Column1=df.Column1.str.replace('\d+','')
    

    【讨论】:

    • 谢谢!答案似乎总是那么简单,但我永远也想不出来 D:
    • 在最后添加一个 .str.strip() 格式完美。
    【解决方案2】:

    仅删除数字会留下不需要的空格字符。

    这个列表推导会删除所有数字并保留 空格字符,但在外面删除它们。

    df['Column2'] = df['Column1'].apply(
                       lambda x: ''.join([i for i in x if not i.isdigit()]).strip())
    

    【讨论】:

    • 完美运行!
    猜你喜欢
    • 2012-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    • 2018-07-23
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    相关资源
    最近更新 更多