Rac*_*hel 8 python formatting dataframe pandas jupyter-notebook
我的数据框中有一些列的长标题,我希望能够包装文本.我知道这个功能内置于熊猫中,就像我一样:
pd.DataFrame(np.random.randn(2, 10),
columns=['Very Long Column Title ' + str(i) for i in range(10)])
Run Code Online (Sandbox Code Playgroud)
但是如果我有更少的列,标题将不会换行:
pd.DataFrame(np.random.randn(10, 2),
columns=['Very Long Column Title ' + str(i) for i in range(2)])
Run Code Online (Sandbox Code Playgroud)
我还尝试手动插入换行符:
import pandas as pd
pd.DataFrame(np.random.randn(10, 2),
columns=['Very Long \n Column Title ' + str(i) for i in range(2)])
Run Code Online (Sandbox Code Playgroud)
但是,它提供与上面相同的输出.
我发现类似的答案有关这个主题:
我正在使用Jupyter笔记本电脑,但如果可能的话,我更喜欢基于熊猫的解决方案.
Jupyter笔记本从许多来源继承了它们的显示属性.没有属性pandas
限制列标题的宽度,因为pandas
它不是导致文本换行的原因,它实际上是呈现的HTML.
您可以使用以下方法覆盖默认的Jupyter Notebook样式以限制表头的最大宽度:
from IPython.core.display import HTML
HTML("<style>.rendered_html th {max-width: 120px;}</style>")
Run Code Online (Sandbox Code Playgroud)
在笔记本顶部运行此代码一次,将html表头的最大列宽设置为120像素.
这是一个不涉及更改IPython属性的答案:
df = pd.DataFrame(np.random.randn(10, 2),
columns=['Very Long Column Title ' + str(i) for i in range(2)])
df.style.set_table_styles([dict(selector="th",props=[('max-width', '50px')])])
Run Code Online (Sandbox Code Playgroud)