首页 > 解决方案 > 恢复原始换行符 pandas \n

问题描述

背景

我有以下示例 df

import pandas as pd
df = pd.DataFrame({'Text' : ['\n[STUFF]\nBut the here is \n\nBase ID : 00000 Date is Here \nfollow\n', 
                                   '\n[OTHER]\n\n\nFound Tom Dub \nhere\n  BATH # : E12-34567 MR # 000', 
                                   '\n[ANY]\nJane Ja So so \nBase ID : 11111 Date\n\n\n hey the \n\n  \n    \n\n\n'],
                    'Alt_Text' : ['[STUFF]But the here is Base ID : *A* Date is Here follow', 
                                   '[OTHER]Found *B* *B* here BATH # : *A* MR # *C*', 
                                   '[ANY]*B* *B*So so Base ID : *A* Date hey the '],


                      'ID': [1,2,3]

                     })

目标

1) 创建一个新列2) 重新获得列中存在New_Text的原始换行符,但包含列中的内容\nTextAlt_Text

例子

Text列,行0

\n[STUFF]\nBut the here is \n\nBase ID : 00000 Date is Here \nfollow\n  

Alt_Text列,行0

[STUFF]But the here is Base ID : *A* Date is Here follow

\n[STUFF]\nBut the here is \n\nBase ID : *A*  Date is Here \nfollow\n   

期望的输出

   Text Alt_Text ID New_Text 
0                   \n[STUFF]\nBut the here is \n\nBase ID :  *A*  Date is Here \nfollow\n  
1                   \n[OTHER]\n\n\nFound *B* *B*  \nhere\n BATH # : *A*  MR # *C*   
2                   \n[ANY]\nJ*B* *B* So so \nBase ID : *A*  Date\n\n\n hey the \n\n \n \n\n\n

试过了

我环顾四周,包括Python 中的 Wrap multiline string (preserving existing linebreaks)?使用 Pandas 读取 Excel 数据并保留单元格值的换行符,但似乎没有一个是我想要做的。

问题

如何实现我想要的输出?

标签: python-3.xpandastextreplaceline-breaks

解决方案


我们正则表达式拆分 TextAlt_Text在模式中使用捕获括号:

如果在模式中使用捕获括号,则模式中所有组的文本也会作为结果列表的一部分返回。

然后我们zip都列出了包含换行符的分隔符Text和其他任何内容,Alt_Text并将join结果列表放入New_Text

def insert_line_breaks(text, alt_text):
    regex = re.compile(r'([^ \n\[\]]+)')
    text = regex.split(text)
    alt_text = regex.split(alt_text)
    return ''.join([t if '\n' in t else a for t,a in zip(text,alt_text)])

df['New_Text'] = df.apply(lambda r: insert_line_breaks(r.Text, r.Alt_Text), axis=1)

我想在所需输出的第二行*B*So最后一行之间应该有一个空格,Alt_Text而在J第一行之前应该是一个错字。*B*在这种情况下,我们得到:

>>> df.New_Text
0            \n[STUFF]\nBut the here is \n\nCase ID : *A* Date is Here \nfollow\n
1                    \n[OTHER]\n\n\nFound *B* *B* \nhere\n  BATH # : *A* MR # *C*
2    \n[ANY]\n*B* *B* So so \nCase ID : *A* Date\n\n\n hey the \n\n  \n    \n\n\n

推荐阅读