keep the extra whitespaces in display of pandas dataframe in jupyter notebook

Viewed 935

In jupyter notebook, extra whitespaces in dataframe are removed. But sometime that is not preferred, e.g.

df=pd.DataFrame({'A':['a   b','c'],'B':[1,2]})
df

The result I get:

|   | A   | B |
|---|-----|---|
| 0 | a b | 1 |
| 1 | c   | 2 |

But I want:

|   | A     | B |
|---|-------|---|
| 0 | a   b | 1 |
| 1 | c     | 2 |

Is it possible? Thanks

1 Answers

It's actually HTML: pandas dutifully write all the spaces into the HTML markup (the front end format used by Jupyter Notebook). HTML, by default, collapses multiple adjacent whitespaces into one. Use the style object to change this:

df.style.set_properties(**{'white-space': 'pre'})

You unfortunately can't change the default render style of a DataFrame yet. You can write a function to wrap that line:

def print_df(df):
    return df.style.set_properties(**{'white-space': 'pre'})

print_df(df)
Related