给出一个包含第2和第3列自由文本的示例数据框,例如
>>> 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列中的字符串以实现:
>>> pd.DataFrame(lol)
0 1 2 3
0 1 2 abc foo bar
1 3 1 def haha love it
如何通过pandas数据框替换具有特定列空格的换行符?
我试过这个:
>>> 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
但必须有更好/更简单的方法。
答案 0 :(得分:1)
您可以使用以下两种正则表达式替换方法:
>>> df.replace({ r'\A\s+|\s+\Z': '', '\n' : ' '}, regex=True, inplace=True)
>>> df
0 1 2 3
0 1 2 abc foo bar
1 3 1 def haha love it
>>>
<强>详情
'\A\s+|\s+\Z'
- &gt; ''
将像strip()
一样删除所有前导和尾随空格:
\A\s+
- 匹配字符串开头的一个或多个空白符号|
- 或\s+\Z
- 匹配字符串末尾的一个或多个空格符号'\n'
- &gt; ' '
将使用空格替换任何换行符。答案 1 :(得分:1)
您可以select_dtypes
选择object
类型的列,并在这些列上使用applymap
。
因为这些函数没有inplace
参数,所以这将是对数据框进行更改的解决方法:
strs = lol.select_dtypes(include=['object']).applymap(lambda x: x.replace('\n', ' ').strip())
lol[strs.columns] = strs
lol
# 0 1 2 3
#0 1 2 abc foo bar
#1 3 1 def haha love it
答案 2 :(得分:1)
添加其他不错的答案,这是您最初想法的矢量化版本:
columns = [2,3]
df.iloc[:, columns] = [df.iloc[:,col].str.strip().str.replace('\n',' ')
for col in columns]
详细信息:
In [49]: df.iloc[:, columns] = [df.iloc[:,col].str.strip().str.replace('\n',' ')
for col in columns]
In [50]: df
Out[50]:
0 1 2 3
0 1 2 abc def haha
1 3 1 foo bar love it
答案 3 :(得分:1)
使用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