【问题标题】:How to remove non-alpha-numeric characters from strings within a dataframe column in Python?如何从 Python 的数据框列中的字符串中删除非字母数字字符?
【发布时间】:2018-02-24 17:42:00
【问题描述】:

我有一个 DF 列,其中包含许多字符串。我需要从该列中删除所有非字母数字字符:即:

df['strings'] = ["a#bc1!","a(b$c"]

运行代码:

Print(df['strings']): ['abc','abc']

我试过了:

df['strings'].replace([',','.','/','"',':',';','!','@','#','$','%',"'","*","(",")","&",],"")

但这不起作用,我觉得应该有一种更有效的方法来使用正则表达式来做到这一点。任何帮助将不胜感激。

【问题讨论】:

    标签: python regex pandas dataframe


    【解决方案1】:

    使用str.replace。

    df
      strings
    0  a#bc1!
    1   a(b$c
    
    df.strings.str.replace('[^a-zA-Z]', '')
    0    abc
    1    abc
    Name: strings, dtype: object
    

    要保留 字母数字 个字符(而不仅仅是您预期的输出建议的字母),您需要:

    df.strings.str.replace('\W', '')
    0    abc1
    1     abc
    Name: strings, dtype: object 
    

    【讨论】:

      【解决方案2】:

      由于您编写的是字母数字,因此您需要在正则表达式中添加 0-9。 但也许你只想要字母...

      import pandas as pd
      
      ded = pd.DataFrame({'strings': ['a#bc1!', 'a(b$c']})
      
      ded.strings.str.replace('[^a-zA-Z0-9]', '')
      

      但这基本上是COLDSPEED写的

      【讨论】:

      • 这是正确的,我必须添加 0-9 和空格,因为我想要这个,但是coldspeed 的答案是第一个并且是正确的方法。
      【解决方案3】:

      你也可以使用正则表达式

      import re
      
      regex = re.compile('[^a-zA-Z]')
      
      l = ["a#bc1!","a(b$c"]
      
      print [regex.sub('', i) for i in l]
      
      ['abc', 'abc']
      

      【讨论】:

        猜你喜欢
        • 2019-11-26
        • 2022-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-26
        • 2013-04-30
        • 1970-01-01
        相关资源
        最近更新 更多