4.10. Style a DataFrame

4.10.1. Highlight your pandas DataFrame

Have you ever wanted to highlight your pandas DataFrame to analyze it easier? For example, positive values will be highlighted as green and negative values will be highlighted as red.

That could be done with df.style.apply(highlight_condition_func).

import pandas as pd 

df = pd.DataFrame({"col1": [-5, -2, 1, 4], "col2": [2, 3, -1, 4]})
def highlight_number(row):
    return [
        "background-color: red; color: white"
        if cell <= 0
        else "background-color: green; color: white"
        for cell in row
    ]
df.style.apply(highlight_number)
  col1 col2
0 -5 2
1 -2 3
2 1 -1
3 4 4

4.10.2. to_markdown: Print a DataFrame in Markdown Format

Sometimes, you might want to include a table in a markdown, such as GitHub README. If you want to print a DataFrame in markdown format, use to_markdown().

import pandas as pd  

df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [5, 6, 7, 8]})
print(df.to_markdown())
|    |   a |   b |
|---:|----:|----:|
|  0 |   1 |   5 |
|  1 |   2 |   6 |
|  2 |   3 |   7 |
|  3 |   4 |   8 |

Copy and paste the output above in Jupyter Notebook’s markdown cell will give you an output like below:

a

b

0

1

5

1

2

6

2

3

7

3

4

8

You can also output markdown with a tabulate option:

print(df.to_markdown(tablefmt="grid"))
+----+-----+-----+
|    |   a |   b |
+====+=====+=====+
|  0 |   1 |   5 |
+----+-----+-----+
|  1 |   2 |   6 |
+----+-----+-----+
|  2 |   3 |   7 |
+----+-----+-----+
|  3 |   4 |   8 |
+----+-----+-----+