7

I'm probably have a simple question but I can't seem to find a solution online. If I create a dataframe "df" in a Jupyter notebook and then I print it out using print(), the table displayed in my broswer does not show any borders at all. For example:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.rand(5,2), columns=["a","b"])
print(df)

This will show a table with no border. I read Jupyter pandas.DataFrame output table format configuration but that seems to help if I simply type

df.head()

not the output of the print() function. Does somebody have any suggestions? Many thanks

nahusznaj
  • 463
  • 4
  • 15
Angelo
  • 1,594
  • 5
  • 17
  • 50
  • `print()` calls `__str__()` (or `__repr__()`) on the object so will turn it into a string. `df.head()` is equivalent to `from IPython.display import display; display(df.head())`. You can just type `df` and it will do the same thing for the whole table. – AChampion Apr 17 '18 at 22:12

3 Answers3

18

@Angel, you can add this script in any cell to introduce table borders. Use df instead of print(df)

%%HTML
<style type="text/css">
table.dataframe td, table.dataframe th {
    border: 1px  black solid !important;
  color: black !important;
}
</style>

enter image description here

Anton Golubev
  • 1,333
  • 12
  • 21
MEdwin
  • 2,940
  • 1
  • 14
  • 27
  • thank you! May I ask where I could read more about that code in case I want to learn? Any suggestions? – Angelo Aug 16 '18 at 18:08
  • 1
    @Angelo.. yes. There are alot of information online. Let me explain to you. What you have is actually calling in python notebook is the inline 'HTML' and adjusting the css part of datatable td/th. You can learn alot of css from here 1. https://www.w3schools.com/css/ and here 2. https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/How_CSS_works – MEdwin Aug 17 '18 at 08:32
  • Nice, but how do you apply this to only one output and not all the dataframes? Thanks! – Newbielp Dec 23 '20 at 12:57
6

Instead of print(df) you use:

from IPython.display import display
display(df)
3

The answer of @MEdwin is perfect, just need to close the style tag, otherwise the broken HTML results in 'eated up' output of several output cells, which follows the HTML code.

%%HTML
<style type="text/css">
table.dataframe td, table.dataframe th {
    border: 1px  black solid !important;
  color: black !important;
}
</style>
Anton Golubev
  • 1,333
  • 12
  • 21