python - 向 Pandas Dataframe 对象添加样式后,如何将其保存为 PDF?

标签 python pdf pandas dataframe styles

我有一个 Dataframe 并为其添加了样式以突出显示部分等,并且可以轻松呈现为 HTML,但是当尝试另存为 PDF 时,样式丢失了。有人有任何提示吗?

import pandas as pd
import numpy as np
np.random.seed(24)
df = pd.DataFrame({'A':np.linspace(1,10,10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))], axis=1)
df.iloc[0, 2] = np.nan

def color_negative_red(val):
    """
    Takes a scalar and returns a string with
    the css property `'color: red'` for negative
    strings, black otherwise.
    """
    color = 'red' if val < 0 else 'black'
    return 'color: %s' % color

s = df.style.applymap(color_negative_red)

我现在想拿s ,这是一个 pandas.core.style.Styler对象并将 DataFrame 转换为 PDF,同时保存所有格式(将负数突出显示为红色)。有没有一种简单的方法可以做到这一点,或者 Pandas 中的样式机制是否仍在开发中?

最佳答案

不是最好的解决方案,但它确实产生了一个 pdf

import pandas as pd
import numpy as np
np.random.seed(24)
df = pd.DataFrame({'A':np.linspace(1,10,10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))], axis=1)
df.iloc[0, 2] = np.nan

def color_negative_red(val):
    """
    Takes a scalar and returns a string with
    the css property `'color: red'` for negative
    strings, black otherwise.
    """
    color = 'red' if val < 0 else 'black'
    return 'color: %s' % color

s = df.style.applymap(color_negative_red)

import pdfkit
import tempfile

options = {
    'page-size': 'Letter',
    'margin-top': '0.75in',
    'margin-right': '0.75in',
    'margin-bottom': '0.75in',
    'margin-left': '0.75in',
    'encoding': "UTF-8",
    'lowquality': False,
    'quiet':'',
    'custom-header' : [
        ('Accept-Encoding', 'gzip')
    ],
    'cookie': [
        ('cookie-name1', 'cookie-value1'),
        ('cookie-name2', 'cookie-value2'),
    ],
    'no-outline': None
}

tmp = tempfile.NamedTemporaryFile()
with open(tmp.name, 'w') as f:
    f.write(s._repr_html_())
with open(tmp.name, 'r') as f:
    pdfkit.from_file(f, "s.pdf",options=options)
f.close()


display(s)

关于python - 向 Pandas Dataframe 对象添加样式后,如何将其保存为 PDF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38531367/

相关文章:

php - RouteCollection.php 中的 NotFoundHttpException 第 161 行 : in Laravel 5. 2

iOS UIWebView PDF 第一次不显示

python - 如何使用 python 将数据框附加到基于 header 的现有 Excel 文件

python - 从数据框中的数组制作散点图

python - 带有空值的 Pandas 数据透视表列不显示

python - 使用 Python-Selenium 自动化 GMAIL 登录

macos - Mac 终端更改 PDF 作者

python - 通过构造函数创建 MultiIndexed 数据框

python - 将数据帧打印到 CSV 文件,保留非拉丁字符

python - 模块未找到错误 : No module named 'application' [Deploying Django to AWS]