添加样式后如何将 Pandas Dataframe 对象另存为 PDF?

Aja*_*and 5 python pdf styles dataframe pandas

我有一个 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)
Run Code Online (Sandbox Code Playgroud)

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

Geo*_*her 0

不是最好的解决方案,但它确实生成了 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)
Run Code Online (Sandbox Code Playgroud)