通过pandas数据框用空格替换str列的换行符 [英] Replacing newlines with spaces for str columns through pandas dataframe
本文介绍了通过pandas数据框用空格替换str列的换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个包含第 2 和第 3 列自由文本的示例数据框,例如
<预><代码>>>>将熊猫导入为 pd>>>大声笑 = [[1,2,'abc','foo\nbar'], [3,1, 'def\nhaha', '喜欢它\n']]>>>pd.DataFrame(笑)0 1 2 30 1 2 abc foo\nbar1 3 1 def\nhaha 喜欢它\n目标是将 \n
替换为 (空格)并去除第 2 列和第 3 列中的字符串以实现:
如何通过 Pandas 数据框用空格替换特定列的换行符?
我已经试过了:
<预><代码>>>>将熊猫导入为 pd>>>大声笑 = [[1,2,'abc','foo\nbar'], [3,1, 'def\nhaha', '喜欢它\n']]>>>replace_and_strip = lambda x: x.replace('\n', ' ').strip()>>>lol2 = [[replace_and_strip(col) if type(col) == str else col for col in list(row)] for idx, row in pd.DataFrame(lol).iterrows()]>>>pd.DataFrame(lol2)0 1 2 30 1 2 abc foo bar1 3 1 def 哈哈 喜欢但一定有更好/更简单的方法.
解决方案
使用 replace
- 第一个和最后一个条带,然后替换 \n
:
df = df.replace({r'\s+$': '', r'^\s+': ''}, regex=True).replace(r'\n', ' ',正则表达式=真)打印 (df)0 1 2 30 1 2 abc foo bar1 3 1 def 哈哈 喜欢
Given an example dataframe with the 2nd and 3rd columns of free text, e.g.
>>> import pandas as pd
>>> lol = [[1,2,'abc','foo\nbar'], [3,1, 'def\nhaha', 'love it\n']]
>>> pd.DataFrame(lol)
0 1 2 3
0 1 2 abc foo\nbar
1 3 1 def\nhaha love it\n
The goal is to replace the \n
to (whitespace) and strip the string in column 2 and 3 to achieve:
>>> pd.DataFrame(lol)
0 1 2 3
0 1 2 abc foo bar
1 3 1 def haha love it
How to replace newlines with spaces for specific columns through pandas dataframe?
I have tried this:
>>> import pandas as pd
>>> lol = [[1,2,'abc','foo\nbar'], [3,1, 'def\nhaha', 'love it\n']]
>>> replace_and_strip = lambda x: x.replace('\n', ' ').strip()
>>> lol2 = [[replace_and_strip(col) if type(col) == str else col for col in list(row)] for idx, row in pd.DataFrame(lol).iterrows()]
>>> pd.DataFrame(lol2)
0 1 2 3
0 1 2 abc foo bar
1 3 1 def haha love it
But there must be a better/simpler way.
解决方案
Use replace
- first first and last strip and then replace \n
:
df = df.replace({r'\s+$': '', r'^\s+': ''}, regex=True).replace(r'\n', ' ', regex=True)
print (df)
0 1 2 3
0 1 2 abc foo bar
1 3 1 def haha love it
这篇关于通过pandas数据框用空格替换str列的换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文