When I change the style of a pandas.DataFrame
, for instance like so
# color these columns
color_columns = ['roi', 'percent_of_ath']
(portfolio_df
.style
# color negative numbers red
.apply(lambda v: 'color: red' if v < 0 else 'color: black',
subset=color_columns)
# color selected cols light blue
.apply(lambda s: 'background-color: lightblue',
subset=color_columns))
the styles applied to the dataframe are not permanent.
To make them stick I can assign the output of the (portfolio_df ...
part to the same dataframe like so:
portfolio_df = (portfolio_df ...
Displaying this overwritten portfolio_df
in a Jupyter Notebook, I can see the beautifully styled DataFrame. But trying to change the style from within a function that is imported from a module, I fail. I construct the DataFrame in the function, change the style, return the (now) styled DataFrame from the function, display it in the Jupyter Notebook, I see a non-styled DataFrame.
Edit
Inspecting the type of the return value of the styling operation
s = (portfolio_df.style.apply(...
I see this:
>>> type(s)
pandas.io.formats.style.Styler
So the operation does not return a DataFrame, but a ...Styler
object. I was erroneously thinking that I can re-assign this return value to my original DataFrame, thus overwrite it and make the style change permanent.
Question
Is the operation of applying a style to a DataFrame a destructive or non-desctructive operation? The answer seems to be that the style is not changed permanently. Now, how can I make it change permanently?
Edit 2
Viewing the source code of Pandas
, I looked at the docstring for class Styler
(see [1]):
If using in the Jupyter notebook, Styler has defined a ``_repr_html_``
to automatically render itself. Otherwise call Styler.render to get
the generated HTML.
So in a Jupyter notebook, Styler has a method that auto renders the dataframe, respecting the applied style.
Otherwise (in iPython) it creates HTML.
Assigning the return value of the applied style to a variable
s = (portfolio_df.style.apply(...
I can use it in an Jupyter notebook to render the new style.
What I understand is this: I cannot output my dataframe into a Jupyter notebook and expect it to render the new style. But I can output s
to show the new style.
[1] class Styler
in
pandas/pandas/io/formats/style.py
Docstring, line 39.