代码之家  ›  专栏  ›  技术社区  ›  Rob

如何在pandas dataframe中替换字符串中的子字符串

  •  3
  • Rob  · 技术社区  · 7 年前

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

    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'  )
    

    en(The\U Voice\uU(U.S.\U season\U 14),613)

    2 回复  |  直到 7 年前
        1
  •  3
  •   jpp    7 年前

    一种方法是使用 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
    
        2
  •  1
  •   mcard    7 年前

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

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