2016-07-22 16 views
2

Ich habe einen Dataframe und habe Stile hinzugefügt, um Abschnitte usw. hervorzuheben, und kann leicht in HTML rendern, aber beim Versuch, als PDF zu speichern, geht das Styling verloren. Hat jemand irgendwelche Tipps?Wie speichere ich ein Pandas Dataframe-Objekt als PDF, nachdem ich ihm einen Stil hinzugefügt habe?

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) 

Ich möchte s jetzt nehmen, was ein pandas.core.style.Styler Objekt ist und die Datenrahmen in eine PDF konvertieren, während alle Formatierungen (Hervorhebung negative Zahlen als rot) zu speichern. Gibt es einen einfachen Weg dies zu tun oder ist der Stilmechanismus in Pandas noch in der Entwicklung?

+0

Verwenden Sie ipython/jupytet? – Merlin

+0

@merlin, ja, ich verwende eine jupyter Notebook-Instanz, um einen Proof of Concept für eine Styling-Datenrahmenfunktion zu erstellen. –

+0

Ich versuche diese letzten zwei Stunden zu retten, es scheint als gäbe es keinen einfachen Weg (ich habe auch keinen schwer gefunden). Pitty, würde ich denken, dass diese Funktion sehr einfach hinzuzufügen wäre, da der HTML-Rohcode irgendwo unter der Haube liegen sollte. – quapka

Antwort

0

Nicht die beste Lösung, aber es tut produzieren eine 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)