【问题标题】:How to replace substrings in strings in pandas dataframe如何替换熊猫数据框中字符串中的子字符串
【发布时间】:2018-09-24 19:48:06
【问题描述】:

我有一个数据框,以及我想从该数据框的列中删除的字符串列表。但是当我使用替换功能时,这些字符仍然存在。有人可以解释一下为什么会这样吗?

bad_chars = ['?', '!', ',', ';', "'", '|', '-', '--', '(', ')', 
             '[', ']', '{', '}', ':', '&', '\n']

并替换:

df2['page'] = df2['page'].replace(bad_chars, '')

当我打印出df2:

for index, row in df2.iterrows():
    print( row['project'] + '\t' + '(' + row['page'] + ',' + str(row['viewCount']) + ')' + '\n'  )

zh (The_Voice_(U.S._season_14),613)

【问题讨论】:

    标签: python string python-3.x pandas dataframe


    【解决方案1】:

    一种方法是使用re 转义你的字符,然后使用pd.Series.str.replace

    import pandas as pd
    import re
    
    bad_chars = ['?', '!', ',', ';', "'", '|', '-', '--', '(', ')', 
                 '[', ']', '{', '}', ':', '&', '\n']
    
    df = pd.DataFrame({'page': ['hello?', 'problems|here', 'nothingwronghere', 'nobrackets[]']})
    
    df['page'] = df['page'].str.replace('|'.join([re.escape(s) for s in bad_chars]), '')
    
    print(df)
    
    #                page
    # 0             hello
    # 1      problemshere
    # 2  nothingwronghere
    # 3        nobrackets
    

    【讨论】:

    • 非常感谢 jpp,做得很好
    【解决方案2】:

    使用.str.replace,并将您的字符串作为一个单独的、管道分隔的字符串传递。正如@jpp 所建议的那样,您可以使用re.escape() 来转义该字符串中的正则表达式字符。我通过避免迭代来稍微调整他的建议:

    import re 
    df2['page'] = df2['page'].str.replace(re.escape('|'.join(bad_chars)), '')
    

    【讨论】:

    • Cheers mcard,当我这样做时,我得到错误: TypeError: unhashable type: 'list' 如果我用该列表中某个元素的文字示例替换列表变量,它仍然有效。有没有办法同时替换多个字符串?
    • 这在一般情况下不起作用,例如你的坏字符列表中的正则表达式字符(例如|)呢?
    • 他们需要用 ´\´ 转义
    • 那么唯一的方法是手动逐个检查坏字符列表以检查转义吗?我敢肯定有更好的方法...
    • 感谢大家的讨论,我接受 jpp 的回答,因为它以一种通用的方式完全符合我的要求。
    猜你喜欢
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 2022-10-13
    • 2018-08-01
    • 2017-07-08
    • 2017-09-09
    • 2022-07-27
    相关资源
    最近更新 更多