【发布时间】:2020-05-11 18:51:55
【问题描述】:
我正在尝试从整个 pandas 数据框中删除所有 \n。我知道在堆栈溢出方面已经有了答案,但由于某些原因,我无法获得所需的输出。我有以下数据框:
title text date authors
0 [ECB completes foreign reserves investment in ... [\nThe European Central Bank (ECB) completed an ... [13 June 2017] ECB
1 [Measures to improve the efficiency of the ope... [\nThe Governing Council of the ECB has decided ... [\n 23 January 2003 \n ] ECB
2 [] [] [] ECB
3 [ECB publishes the results of the Euro Money M... [Today the European Central Bank (ECB) is publ... [\n 28 September 2012 \n ] ECB
4 [] [] [] ECB
这是我想要的输出:
title text date authors
0 [ECB completes foreign reserves investment in... [The European Central Bank (ECB) completed an ... [13 June 2017] ECB
1 [Measures to improve the efficiency of the ope... [The Governing Council of the ECB has decided ... [23 January 2003] ECB
2 [] [] [] ECB
3 [ECB publishes the results of the Euro Money M... [Today the European Central Bank (ECB) is publ... [28 September 2012] ECB
4 [] [] [] ECB
这些都是我试过的代码:
-
基于我尝试过的this stack overflow 帖子:
mydf=df.replace({r'\\n': ''}, regex=True) mydf=df['date'].str.strip(r'\\n') #this turns every obs into NaN mydf=df.replace(to_replace=[r"\\n", "\n"], value=["",""], regex=True, inplace =True) #this gets rid of all data in dataframe for some reason
这两种方法都不起作用
-
基于我尝试过的this post(注意我跳过了之前已经尝试过的答案):
mydf=df.replace(r'\s', '', regex = True, inplace = True) #this deleted all data -
基于this post我试过了:
mydf=df.replace('\\n',' ') -
基于 this post 的 cmets 我试过了:
mydf=df['date'].replace(r'\s+|\\n', ' ', regex=True, inplace=True)和mydf=df.replace(r'\s+|\\n', ' ', regex=True, inplace=True) -
根据我尝试过的this post 中的答案:
mydf= df.replace({r'\s+$': '', r'^\s+': ''}, regex=True).replace(r'\n', ' ', regex=True)mydf=df.replace({ r'\A\s+|\s+\Z': '', '\n' : ' '}, regex=True, inplace=True) # this again deleted whole df
我不明白为什么在那里找到的答案在我的案例中不起作用,因为它们被接受了,而且大多数问题似乎与我的非常相似。
【问题讨论】:
-
您能否提供一个示例 df,我们可以将其复制到浏览器中?
-
@Datanovice 当然,我应该导出 df 并将其上传到某个地方,还是 python 中的代码可以给我输出,我可以在这里复制粘贴?
标签: python-3.x pandas data-cleaning