如何防止HTML代码在quarto gfm报告中出现在pandas表格上方

1 投票
1 回答
34 浏览
提问于 2025-04-14 16:00

当我在quarto gfm报告中显示一个pandas表格时,在GitHub上查看报告时,我看到表格上方有一些HTML代码。我该如何避免这种情况呢?

在这里输入图片描述

生成上述报告的Qmd文件中的代码

---
title: 'HTML junk'
author: 'Joseph Powers'
date: 2024-03-14
format: gfm
---

```{python}
import numpy as np
import pandas as pd
```

# Notice the html code above the table
```{python}
N = int(5e3)
TRIALS = int(1)

pd.DataFrame(
    {
        "A": np.random.binomial(TRIALS,  0.65, N),
        "B": np.random.binomial(TRIALS,  0.65, N),
        "C": np.random.binomial(TRIALS,  0.65, N),
        "D": np.random.binomial(TRIALS,  0.67, N)
    }
)
```

1 个回答

1

可以使用 print(pd.DataFrame.to_markdown()) 这个方法,来以适合Markdown格式的方式打印DataFrame。同时,使用quarto的选项 output: asis,可以得到未经处理的原始Markdown表格。渲染完源文件qmd后,你会发现生成的Markdown文件这次没有包含任何HTML代码。

---
title: 'HTML junk'
author: 'Joseph Powers'
date: 2024-03-14
format: gfm
---

```{python}
import numpy as np
import pandas as pd
```

# Notice the html code above the table
```{python}
#| output: "asis"
N = int(5e3)
TRIALS = int(1)

df = pd.DataFrame(
    {
        "A": np.random.binomial(TRIALS,  0.65, N),
        "B": np.random.binomial(TRIALS,  0.65, N),
        "C": np.random.binomial(TRIALS,  0.65, N),
        "D": np.random.binomial(TRIALS,  0.67, N)
    }
)

print(df.to_markdown())
```

撰写回答