python-3.x - 从 pandas 数据框中删除\n 的问题

标签 python-3.x pandas data-cleaning

我正在尝试从整个 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 删除所有数据

  2. 基于 this post我试过:

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

  3. 基于对 this post 的评论我试过:

    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', ' ',正则表达式=真)

    mydf=df.replace({ r'\A\s+|\s+\Z': '', '\n' : ' '}, regex=True, inplace=True) # 这又被删除了整个df

我不明白为什么在那里找到的答案在我的案例中不起作用,因为它们已被接受,而且大多数问题似乎与我的问题非常相似。

最佳答案

尝试:

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'&&')

关于python-3.x - 从 pandas 数据框中删除\n 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59913472/

相关文章:

r - 如何在 R 中轻松格式化频率表?

python - 将 Ruby 中的 json 响应移植到 Python

python - 将 2010 Q1 转换为日期时间 2010-3-31

multithreading - 从 python3 中的 multiprocess.proccess 更新 tk ProgressBar

Python Pandas : force to save a df in a csv numerical values with 4 digits

python - 如何将数据集读入 pandas 并忽略列数不均匀的行

python - 在pandas dataframe python中减去两行的一系列列

python - 如何根据条件连接同一列的值?

python - 在 Python 3 中替换 docx 表中的文本

Python函数执行顺序