简体   繁体   中英

styling a pandas dataframe in python makes the float values have more zeros after the decimal point

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)



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)

图片

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM