给出一个包含第2列和第3列自由文本的示例dataframe,例如
>>> 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
目标是将\n
替换为(空白),并去掉第2列和第3列中的字符串,以实现:
如何通过pandas dataframe将新行替换为特定列的空格?
我试过了:
>>> 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
但必须有更好/更简单的方法。在
您可以使用以下两种正则表达式替换方法:
详细信息
'\A\s+|\s+\Z'
->;''
的作用类似于strip()
删除所有前导和尾随空格:\A\s+
-匹配字符串开头的一个或多个空白符号|
-或\s+\Z
-匹配字符串末尾的一个或多个空白符号'\n'
->;' '
将用空格替换任何换行符。在使用^{} -第一个和最后一个条带,然后替换
\n
:您可以
select_dtypes
来选择object
类型的列,并在这些列上使用applymap
。在因为这些函数没有
inplace
参数,所以这是对数据帧进行更改的解决方法:相关问题 更多 >
编程相关推荐