0

I would like to change the style of my pandas without changing its type

Here a small example

import pandas as pd
df = pd.DataFrame([[19, 439],[19, 439]], columns=['COOL','NOTCOOL'])
def colour_col(col):
    if col.name == 'COOL':    
        return ['background-color: red'  for c in col.values]
df = df.style.apply(colour_col)
df

enter image description here

But, obviously df is now a pandas.io.formats.style.Styler, so I can not have access to 'COOL' column anymore

df['COOL']
TypeError: 'Styler' object is not subscriptable

How can I customize my pandas only when it is displayed ?

olivier dadoun
  • 622
  • 6
  • 22
  • Why do you assign the return value to `df`? Running `df.style.apply(colour_col)` should modify the `Styler` object directly see https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.io.formats.style.Styler.apply.html?highlight=style%20apply – Tranbi Mar 16 '23 at 10:08
  • There is a SO question regarding changing style permanently: https://stackoverflow.com/questions/56176720/changing-style-of-pandas-dataframe-permanently Maybe that's what you're after? – Tranbi Mar 16 '23 at 10:13
  • True. But behind that I have a function. I want to have the possibility to return a pimped pandas when one want to display it or a pandas when one want to save it into an other variable (to be able to make some calculation after) – olivier dadoun Mar 16 '23 at 10:15

1 Answers1

0

A simple solution is to make a function which print (display) the pandas pimped and return the pandas Dataframe

import pandas as pd
df = pd.DataFrame([[19, 439],[19, 439]], columns=['COOL','NOTCOOL'])

def toto(mypd):
    def colour_col(col):
        if col.name == 'COOL':    
            return ['background-color: red'  for c in col.values]
    display(mypd.style.apply(colour_col))
    return mypd
A=toto(df)
A['COOL']
[![enter image description here][1]][1]
olivier dadoun
  • 622
  • 6
  • 22
  • the simplest solution is to create a dataframe, `df` and not overwrite it. Then it is always available as an object, you do not need to "return" it. The styler can display in any customised form you like with one call: `df.style.pipe(my_custom)` – Attack68 Mar 21 '23 at 22:42