Search code examples
pythonpandasdataframegoogle-colaboratory

How to display a list of dataframes in a specific style?


I have cleaned my data set and separated blocks of code in different dataframes. These dataframes are put in a list. Individually, it works fine but in loop, I don't get any output.

def trialflag(x):
  default=''
  green='background-color: green'
  blue='background-color: blue'
  yellow='background-color: yellow'
  orange='background-color: orange'
  red='background-color: red'
  g= x['THI Flag'] == "Green"
  b= x['THI Flag'] == "Blue"
  y= x['THI Flag'] == "Yellow"
  o= x['THI Flag'] == "Orange"
  r= x['THI Flag'] == "Red"
  df1 = pd.DataFrame(default, index=x.index, columns=x.columns)
  df1.loc[g, ['THI','THI Flag']] = green
  df1.loc[b,['THI','THI Flag']]= blue
  df1.loc[y, ['THI','THI Flag']] = yellow
  df1.loc[o,['THI','THI Flag']] = orange
  df1.loc[r,['THI','THI Flag']] = red
  return df1

for i in range(0,ntrans):
  (transformerlist[I].head(5))[['Meter_Serial_Number','THI','THI Flag','THI Action']].style.apply(trialflag,axis=None)

Output:(I get nothing)


For this example:

def trialflag(x):
  default=''
  green='background-color: green'
  blue='background-color: blue'
  yellow='background-color: yellow'
  orange='background-color: orange'
  red='background-color: red'
  g= x['THI Flag'] == "Green"
  b= x['THI Flag'] == "Blue"
  y= x['THI Flag'] == "Yellow"
  o= x['THI Flag'] == "Orange"
  r= x['THI Flag'] == "Red"
  df1 = pd.DataFrame(default, index=x.index, columns=x.columns)
  df1.loc[g, ['THI','THI Flag']] = green
  df1.loc[b,['THI','THI Flag']]= blue
  df1.loc[y, ['THI','THI Flag']] = yellow
  df1.loc[o,['THI','THI Flag']] = orange
  df1.loc[r,['THI','THI Flag']] = red
  return df1

transdup=transformerlist[0]
transformerlist[0].head(5)[['Meter_Serial_Number','THI','THI Flag']].style.apply(trialflag,axis=None)

Output: Click to see image

I am trying to get an output where it shows that style for every dataframe in transformerlist. Any thoughts and suggestions would be highly appreciated!


Solution

  • You need to call display in the loop.

    for df in df_list:
        df = df.style.apply(trialflag,axis=None)
        display(df)