【问题标题】:remove punctuation for each row in a pandas data frame [duplicate]删除熊猫数据框中每一行的标点符号[重复]
【发布时间】:2016-01-07 23:11:20
【问题描述】:

我是 python 新手,所以这可能是一个非常基本的问题。我正在尝试使用 lambda 删除熊猫数据框中每一行的标点符号。我使用了以下内容,但收到了错误。我试图避免将 df 转换为列表,然后将清理后的结果附加到新列表中,然后将其转换回 df。

任何建议将不胜感激!

import string

df['cleaned'] = df['old'].apply(lambda x: x.replace(c,'') for c in string.punctuation)

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您需要遍历数据框中的字符串,而不是遍历string.punctuation。您还需要使用.join() 备份字符串。

    df['cleaned'] = df['old'].apply(lambda x:''.join([i for i in x 
                                                      if i not in string.punctuation]))
    

    当 lambda 表达式变得像那样长时,单独写出函数定义会更具可读性,例如(感谢@AndyHayden 的优化提示):

    def remove_punctuation(s):
        s = ''.join([i for i in s if i not in frozenset(string.punctuation)])
        return s
    
    df['cleaned'] = df['old'].apply(remove_punctuation)
    

    【讨论】:

    • 不客气!
    • 如果它适合你,你可以接受这个答案。
    • 这里的一个改进是在 remove_punctuation 中使用 set(string.punctuation) 而不是 string.punctuation。
    • 谢谢,安迪。我会把它添加进去。
    • 连接周围的方括号/列表理解给你另一个提升fwiw :)
    【解决方案2】:

    在这里使用正则表达式很可能会更快:

    In [11]: RE_PUNCTUATION = '|'.join([re.escape(x) for x in string.punctuation])  # perhaps this is available in the re/regex library?
    
    In [12]: s = pd.Series(["a..b", "c<=d", "e|}f"])
    
    In [13]: s.str.replace(RE_PUNCTUATION, "")
    Out[13]:
    0    ab
    1    cd
    2    ef
    dtype: object
    

    【讨论】:

    • 这应该是公认的答案...
    • 类似:s.str.replace('[{}]'.format(string.punctuation), '')
    猜你喜欢
    • 2017-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-04
    • 2020-03-23
    • 1970-01-01
    • 2021-12-02
    • 2017-10-04
    相关资源
    最近更新 更多