Apply Pandas Style to All Dataframes in Jupyter Notebook
Asked Answered
M

2

8

In Jupyter notebooks with many Pandas Dataframes, is there a way to set default Style options for all dataframes? Essentially to avoid boilerplate.

For example Hiding-the-Index-or-Columns with df.style.hide_index() for all dataframes.

Yes, I could write wrapper function, but thinking more of something like pd.options.display

Mansoor answered 29/2, 2020 at 12:21 Comment(2)
Did you find a solution to this?Michelinamicheline
Unfortunately no.Angara
S
1

One solution would be to inherit the pd.DataFrame class (aka creating a subclass of pd.DataFrame) as described in the official docs. then you can modify its constructor to change the style. The class should be like this:

class CustomDataFrame(pd.DataFrame):

    @property
    def _constructor(self):
      # change style. you can move this into another function as well.
       self.style \
        .format(precision=3, thousands=".", decimal=",") \
        .format_index(str.upper, axis=1) \
        .hide(axis="index")
      # return an instance of CustomDataFrame
       return CustomDataFrame

Then, you can use this class the same as the pd.DataFrame. For example run this:

data = [['Mj', 27], ['Sarah', 5]]

df = CustomDataFrame(data, columns = ['Name', 'Age'])
df.head() 
Snuggery answered 4/3 at 8:38 Comment(0)
D
0

if you are using lots of dataframes you could find dataframes in your workspace and then apply style to each one of them

workspace = dir() #gets all variables in workspace
for variable_name in workspace:
    excec( f'var_type=type({variable_name})' ) #since we have access to only the names of variables we'll use exec
    if var_type== pd.Dataframe():#check to see if the variable is of type dataframe
        #apply style here
Doreendorelia answered 16/5, 2023 at 11:37 Comment(1)
This solution looks okay, but it only solves the problem completely if the styling only matters after every dataframe is created. Otherwise, it would have to be run on every dataframe creation, and then calling a wrapper is simpler.Acima

© 2022 - 2024 — McMap. All rights reserved.