0

The following code (which I got from a different SO question) is supposed to print out a table with some colored cells. However, it does not print in color:

import pandas as pd
from IPython.core.display import HTML
from IPython.display import display

df = pd.DataFrame([[2,3,1], [3,2,2], [2,4,4]], columns=list("ABC"))

df.style.apply(lambda x: ["background: red" if v > x.iloc[0] else "" for v in x], axis = 1)
df
print(df)
display(df)
display(HTML(df.to_html()))
print('hi')

Here's a screenshot: jupyter-notebook screenshot of script execution

But, as per the SO example I linked to above, it's supposed to look like this: example of what the table is supposed to look like

This may be some useful information:

(stats_env) raj@r-sb2:~/repos/fix_print$ jupyter --version
jupyter core     : 4.6.3
jupyter-notebook : 6.1.1
qtconsole        : not installed
ipython          : 7.17.0
ipykernel        : 5.3.4
jupyter client   : 6.1.6
jupyter lab      : not installed
nbconvert        : 5.6.1
ipywidgets       : not installed
nbformat         : 5.0.7
traitlets        : 4.3.3
Raj
  • 1,555
  • 18
  • 32

1 Answers1

1

you are printing the df again! comment the last part. It will work.

import pandas as pd
from IPython.core.display import HTML
from IPython.display import display

df = pd.DataFrame([[2,3,1], [3,2,2], [2,4,4]], columns=list("ABC"))

df.style.apply(lambda x: ['background: red' if v > x.iloc[0] else "" for v in x], axis = 1)
# df
# print(df)
# display(df)
# display(HTML(df.to_html()))
rmb
  • 553
  • 5
  • 15
  • Yes, that appears to have worked https://i.imgur.com/n3kZxUv.png , thank you! However, how would I reprint it if needed? Or, how can I save the style onto this df or in a new df (and then print it as needed)? – Raj Aug 26 '20 at 04:54
  • just put it inside a new variable name `df_new = df.style.apply(lambda x: ['background: red' if v > x.iloc[0] else "" for v in x], axis = 1)` – rmb Aug 26 '20 at 04:58
  • THANK YOU, IT WORKED! I could swear I tried that before and it hadn't worked. Why doesn't this print out the `df2` multiple times, as one would expect? https://i.imgur.com/64Qf6E2.png Additionally, what if I wanted to print out the `df` from within a function (without returning it from the function) https://i.imgur.com/XXjoDsz.png ? I will mark you as the answer anyway, but I believe your answer will be amazing if you can incorporate those two responses in an edited answer above. – Raj Aug 26 '20 at 05:01
  • Jupyter doesnt work like that. You might want to look into this https://stackoverflow.com/questions/36786722/how-to-display-full-output-in-jupyter-not-only-last-result – rmb Aug 26 '20 at 05:05
  • That didn't work unfortunately: https://i.imgur.com/AGgPnae.png – Raj Aug 26 '20 at 05:10