英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论