我是Python的新手,但我正在尝试在R Markdown块内呈现使用以下Python代码生成的表格。当在Jupyter中运行时,Python代码会输出一个漂亮格式的表格,但我似乎无法在Markdown文档中复制它。
{python, engine.path = '/usr/bin/python3'}
import pandas as pd
import numpy as np
df1 = pd.read_csv(r'./data/crest_results_table.txt', sep='\t')
df2 = pd.read_csv(r'./data/crest_formats_table.txt', sep='\t')
results_table = df1.pivot_table(values=['Result'],index=['Anlys_Mthd','CAS','AnalTParam','RDCSRS','NRDCSRS','IGWSRS'],columns=['SampNum','LabID','SampDate'],aggfunc=np.max)
formats_table = df2.pivot_table(values=['Result'],index=['Anlys_Mthd','CAS','AnalTParam','RDCSRS','NRDCSRS','IGWSRS'],columns=['SampNum','LabID','SampDate'],aggfunc=np.max)
def color_cells(s):
if s == -1:
return 'color:{0}; background-color: white; font-weight:bold; font-style:italic; font-size:small'.format('black')
elif s == -2:
return 'color:{0}; background-color: orange; font-weight:bold; font-style:italic; font-size:small'.format('black')
elif s == -3:
return 'color:{0}; background-color: yellow; font-weight:bold; font-size:small'.format('black')
elif s == -4:
return 'color:{0}; background-color: beige; font-weight:bold; font-size:small'.format('black')
else:
return 'color:{0}; font-size:small'.format('grey')
t = results_table.style.apply(lambda x: formats_table.applymap(color_cells), axis=None)
ht = t.render()
我试过使用render()方法将其保存为html,然后在一个R代码块中保存或打印它。
{r}
htmltools::save_html(py$ht, "table.html")
htmltools::html_print(py$ht)
然而,当我查看保存的html文件时,即使在浏览器中,也无法正确呈现。
pandas文档提到了“将其包装在IPython.display.HTML中”,但由于不了解任何python,我不确定这意味着什么。
理想情况下,我希望markdown块可以像jupyter一样使用相同的代码格式化相同的表格。
谢谢