【问题标题】:Issue with removing \n from pandas dataframe从熊猫数据框中删除 \n 的问题
【发布时间】: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 

这些都是我试过的代码:

  1. 基于我尝试过的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
    

这两种方法都不起作用

  1. 基于我尝试过的this post(注意我跳过了之前已经尝试过的答案):

    mydf=df.replace(r'\s', '', regex = True, inplace = True) #this deleted all data

  2. 基于this post我试过了:

    mydf=df.replace('\\n',' ')

  3. 基于 this post 的 cmets 我试过了:

    mydf=df['date'].replace(r'\s+|\\n', ' ', regex=True, inplace=True)

    mydf=df.replace(r'\s+|\\n', ' ', regex=True, inplace=True)

  4. 根据我尝试过的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


【解决方案1】:
d = {'col1': [['\n a b c'], ['\n x y z']], 'col2': [[1.5000], ['\n x y z']]}
df20 = pd.DataFrame(data=d)

print(df20)

def remove_spec_char(string_list=list):
    y = []
    for string_x in string_list:
        if type(string_x) == str:
            y.append(string_x.replace('\n', ''))
        else:
            y.append(string_x)
    return y



for c in df20.columns:

    df20[c] = df20[c].apply(remove_spec_char)

print(df20)

【讨论】:

  • 我试过这个:def remove_spec_char(string_x=str): return string_x.replace('\n', '') for c in df.columns: df[c] = df[c].apply(remove_spec_char) print(df) 但我收到以下错误:AttributeError: 'list' object has no attribute 'replace'
  • 请检查上面的代码,编辑到进程列表
  • 我试过了,但现在它认为该对象是一个浮点数。我收到df[c] = df[c].apply(remove_spec_char) TypeError 的错误:'float' 对象不可迭代。我不明白发生了什么,因为数据框中的所有列都包含文本,所以它们应该是字符串
  • @BhosaleShirkant 代码运行没有错误,但没有产生所需的输出。 Grzegorz Skibinski 的答案对我有用,所以我不再需要帮助,但我给你 +1,因为我感谢你在答案中付出的所有努力
【解决方案2】:

试试:

df['date']=df['date'].str[0].str.replace(r"\n", "")

这是在假设 date 列中的每个单元格是一个只有 1 个元素的列表的情况下。它也会将其展平 - 因此您将从该单个元素中获取字符串。

如果 date 可以包含多个元素,并且您希望在摆脱所有 \n 后将它们全部合并为单个字符串 - 尝试

df['date']=df['date'].str.join('').str.replace(r"\n", "")

否则,如果您希望将其保留为列表格式,只需剥离 \n 的所有元素尝试(&& 是临时分隔符):

df['date']=df['date'].str.join(r'&&').str.replace(r"\n", "").str.split(r'&&')

【讨论】:

  • 感谢这工作!顺便说一句,我对 .str[0] 很感兴趣,通常当您检查列表时,list[0] 会为您提供列表中的第一个条目,数据框中的 str[0] 是否指的是整个列?我之所以问,是因为我从第一眼开始就对此感到有些困惑,我认为这只会纠正第一次约会而不是所有约会
  • 很高兴听到这个消息:) .str[0] 是获取列表第一项的方法,但作为矢量化函数,即如果您有 pandas.Series 并且每一行都有一个可迭代的,它将为每一行的可迭代返回第一个元素。
  • 哦,知道了,我虽然你总是需要某种 for 循环,但很高兴知道。感谢大家的帮助!
猜你喜欢
  • 2016-08-09
  • 2021-10-31
  • 1970-01-01
  • 1970-01-01
  • 2016-04-30
  • 2020-11-25
  • 2020-03-23
  • 1970-01-01
  • 2020-05-28
相关资源
最近更新 更多