从pandas中删除html格式

2024-10-01 09:26:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个关于熊猫的数据框:

import pandas as pd
df = pd.DataFrame({'CARGO': {53944: 'Driver',
57389: 'Driver',
  60851: 'Driver',
  64322: 'Driver',
  67771: 'Driver'},
 'DATE': {53944: '05/2015',
  57389: '06/2015',
  60851: '07/2015',
  64322: '08/2015',
  67771: '09/2015'},
 'DESCRICAO': {53944: '\\Salario R$ 788,00\nGratificacao Adicional R$ 251,00\nGRATIFICAÇÃO R$ 512,00\nINSS R$ -104,00',
  57389: '\\Salario R$ 788,00\nGratificacao Adicional R$ 251,00\nGRATIFICAÇÃO R$ 512,00\nINSS R$ -104,00',
  60851: '\\Salario R$ 788,00\n1/3 de Ferias R$ 516,95\nGratificacao Adicional R$ 251,00\nGRATIFICAÇÃO R$ 512,00\nINSS R$ -104,00',
  64322: '\\Salario R$ 788,00\nGratificacao Adicional R$ 251,00\nGRATIFICAÇÃO R$ 512,00\nINSS R$ -104,00',
  67771: '\\Salario R$ 788,00\nGratificacao Adicional R$ 225,90\nGRATIFICAÇÃO R$ 512,00\nINSS R$ -104,00'},
 'NOME': {53944: 'John Smith',
  57389: 'John Smith',
  60851: 'John Smith',
  64322: 'John Smith',
  67771: 'John Smith'}})

它呈现以下输出:

enter image description here]

如何设置pandas或Jupyter,使其能够: 1显示纯文本 2接受换行符('\n')

编辑1:

我希望是这样的: enter image description here


Tags: 数据importdataframepandasdfasdriverjohn
3条回答

扩展Psidom的优秀答案,您可以将其封装在一个可重用的函数中。这样,您也不会永久更改数据帧:

from IPython.core.display import HTML

def convert_newlines(s):
    return s.replace('\n', '<br>') if isinstance(s, str) else s

def show_dataframe(df):
    return HTML(df.applymap(convert_newlines).to_html(escape=False)) 

您可以尝试这些方法,将新行字符替换为html换行标记<br>,并显式地使用.to_html()和{}作为显示,还可以将max_colwidth设置为-1,以便在转换为html时不会截断长行:

from IPython.core.display import HTML
pd.set_option('display.max_colwidth', -1)
df['DESCRICAO'] = df['DESCRICAO'].str.replace('\$', '\\$').str.replace('\n', '<br>')
HTML(df.to_html(escape=False))

enter image description here

问题的第一部分解决了。在

在markdown中,$表示mathjax上公式的开始。解决方法是在符号之前插入反斜杠。以下是熊猫的片段:

def fix_dollar_sign(x):
   return re.sub('\$','\\$',x) # remember regex also uses dollar sign.
df['DESCRICAO'] = df['DESCRICAO'].apply(fix_dollar_sign)

一。在

我没能在牢房里划一条新的线。。在

相关问题 更多 >