2017-12-04 2 views
4

Die documentation ein Beispiel zeigt, wie die Schriftfarbe eines Elements auf Wert bedingt zu ändern, die wie erwartet funktioniert gut:Benutzerdefinierte Styling Pandas Dataframe

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) 

Meine Frage ist, wie eine Funktion zu implementieren, anstatt wendet die Schriftfarbenänderung in der ganzen Reihe an?

+0

können Sie einen Beispieldatensatz hinzufügen? – MaxU

Antwort

4

arbeiten Sie mit DataFrame, so dass es Zeile red gesetzt, wenn mindestens ein Wert von weniger als 0 in der Reihe ist:

def color_negative_red(x): 
    c1 = 'background-color: red' 
    c2 = 'background-color: black' 

    df1 = pd.DataFrame(c2, index=x.index, columns=x.columns) 
    df1 = df1.where((x > 0).all(axis=1), c1) 
    return df1 

df.style.apply(color_negative_red, axis=None)