【问题标题】:replace \n from a list in a data frame从数据框中的列表中替换 \n
【发布时间】:2020-04-22 03:27:04
【问题描述】:

我有:

df=pd.DataFrame({'text':[['\nThere are a lot of\n things that \nare worthy','\nS\nU\nP\nE\nR'],['\nAnd there is \nlots to see']]})
df
0   [\nThere are a lot of\n things that \nare wort...
1   [\nAnd there is \nlots to see]

我想替换所有的\n,并保持相同的结构。

我试过了:

df['new']=df.text.str.replace('\n','')
    text    new
0   [\nThere are a lot of\n things that \nare wort...   NaN
1   [\nAnd there is \nlots to see]  NaN

任何建议

【问题讨论】:

  • 为什么是双嵌套列表?如果我尝试使用平面列表,它会起作用

标签: regex pandas


【解决方案1】:

你可以这样做:

import re
df['new'] = df['text'].apply(lambda x: [re.sub(r'\n', '', y) for y in x])

【讨论】:

    【解决方案2】:

    首先,您可以尝试使用另一个转义字符来确保将其作为字符串提取。

    df['new']=df.text.str.replace('\\n','')
    

    第二种情况,我建议将这个答案中解释的方法与“re”库一起使用

    replace special characters in a string python

    【讨论】:

      猜你喜欢
      • 2018-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-31
      • 2020-03-06
      • 2021-01-03
      • 2018-09-14
      相关资源
      最近更新 更多