从数据框中的列表中替换换行符。

huangapple go评论65阅读模式
英文:

replace \n from a list in a data frame

问题

我尝试过:

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

这个代码会替换所有的\n,并保持相同的结构。

英文:

I have:

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]

I want to replace all \n's, and keep the same structure.

I tried:

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

Any suggestions

答案1

得分: 2

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

英文:

You can do:

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

答案2

得分: -1

首先,您可以尝试使用另一个转义字符来确保它被视为字符串。

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

第二种情况,我建议使用此答案中使用 "re" 库解释的方法。

https://stackoverflow.com/questions/23996118/replace-special-characters-in-a-string-python

英文:

First, you can try is to use another escape character to be sure that is fetched as string.

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

Second case, i would suggest to use the method explained in this answer with the "re" library

https://stackoverflow.com/questions/23996118/replace-special-characters-in-a-string-python

huangapple
  • 本文由 发表于 2020年1月3日 22:55:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/59580709.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定