4

this is my style code to make positive numbers appear green and negative numbers appear red if i just print out df it would show the numbers like this:

25.72,36.28,0.17

with the style however they are displayed like this: 25.7200000, 36.2800000, 0.1700000

how would i make them appear like before but with the colorful style? thank you for your help im really new to python

def color_negative_red(value):
    if isinstance(value, str):
        color = 'black'
        return 'color: %s' % color
    if isinstance(value, float):
        if value > 0:
            color = "green"
            return 'color: %s' % color
        if value < 0:
            color = "red"
            return 'color: %s' % color


df.style.applymap(color_negative_red)



Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
xreboorn
  • 43
  • 3

1 Answers1

3

You can specify format for floats columns by dictionary in Styler.format:

df = pd.DataFrame({'a': [25.72,36.28,0.17], 'b': [9.7,-9, 9.8], 'c':list('abc')}) 


def color_negative_red(value):
    if isinstance(value, str):
        color = 'black'
        return 'color: %s' % color
    if isinstance(value, float):
        if value > 0:
            color = "green"
            return 'color: %s' % color
        if value < 0:
            color = "red"
            return 'color: %s' % color

d = dict.fromkeys(df.select_dtypes('float').columns, "{:.2%}")
df.style.applymap(color_negative_red).format(d)

pic

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • The question is not asking how to format floats, but rather that `df.style.applymap` will break the default mechanism of inferring the number of decimal places to display, among other things. For example, by default your 'b' column would have only displayed 1 decimal place in the HTML, the same as in your console output. Your code forces it to display 2 decimal places, which is not the original behavior of the styler. – Moobie May 22 '23 at 23:48