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

只愿长相守 提交于 2021-01-27 19:36:41

问题


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:


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)


来源:https://stackoverflow.com/questions/58562191/keep-the-extra-whitespaces-in-display-of-pandas-dataframe-in-jupyter-notebook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!