Add color for columns files csv by pandas with python

Viewed 3866

I'm trying read data file csv, that done, but I want to write another data with some conditions add style(color, both...) for data in csv file.

i) I read the data from a file csv, is a simple test file first to apply a large data file latter, so the data test is file is

cod     price   var
AMZ     8484    -1.15
BABA    1390    3.5
GOGL    327     -10.5
MSFT    1135    3.3
VISA    6499    2.0
PBB     1055    4.0
CHC     3455    1.1
IFT     5228    -4.0
FRA     4555    2.0

ii) put conditions and read only values which column var > 1

iii) put back ground color in the cod column:

 red where var => 3 
 yellow where var = 2 <3

iv) save in another data csv

my code until moment is:

import pandas as pd

df = pd.read_csv("teste.csv") 
f1 = df['var'] > 1    


df[f1].to_csv('export.csv')

I don't know how use style in pandas, can you please help me this case?

1 Answers

You can try something like this

import numpy as np
import pandas as pd


df = pd.DataFrame([[8484,-1.15],[1390,3.5],[327,10.5],[1135,3.3],[6499,2.0],[1055,4.0]], columns=['data1','dat2'])


def color_rule(val):
    return ['background-color: red' if x >= 3 else 'background-color: yellow' for x in val]

html_column = df.style.apply(color_rule, axis=1, subset=['dat2'])

html_column.to_excel('styled.xlsx', engine='openpyxl')

html_column

#edit: you can export your styled dataframe with to_excel

#edit2: change de color of column 'Cod' instead the column 'var'

import numpy as np
import pandas as pd


df = pd.DataFrame([['ex1',8484,-1.15],['ex2',1390,3.5],['ex3',327,10.5],['ex4',1135,3.3],['ex5',6499,2.0],['ex6',1055,4.0]], columns=['tag','data1','dat2'])


def color_rule(tag):
    var1 = df['dat2'][df['tag'] == tag.values[0]]
    return ['background-color: red' if x >= 3 else 'background-color: yellow' for x in var1]

html_column = df.style.apply(color_rule, axis=1, subset=['tag'])

html_column.to_excel('styled.xlsx', engine='openpyxl')
Related