在Python Pandas DataFrame或Jupyter Notebook中包装列名称 [英] Wrapping column names in Python Pandas DataFrame or Jupyter Notebooks

查看:121
本文介绍了在Python Pandas DataFrame或Jupyter Notebook中包装列名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于数据框中的某些列,我都有很长的标题,我希望能够包装文本.我知道该功能已内置到熊猫中,就像我一样:

I have long titles for some of my columns in my data frame, and I would like the ability to wrap the text. I know that this functionality is built into pandas, as I do:

pd.DataFrame(np.random.randn(2, 10), 
    columns=['Very Long Column Title ' + str(i) for i in range(10)])

带有包装的列名的数据框

但是,如果我的列数较少,标题将不会自动换行:

But if I have fewer columns, the titles will not wrap:

pd.DataFrame(np.random.randn(10, 2), 
    columns=['Very Long Column Title ' + str(i) for i in range(2)])

DataFrame不包装列名

我也尝试过手动插入换行符:

I have also tried to manually insert a newline:

import pandas as pd    
pd.DataFrame(np.random.randn(10, 2), 
    columns=['Very Long \n Column Title ' + str(i) for i in range(2)])

但是给出的输出与上述相同.

But that gives the same output as above.

我已经找到了与此主题类似的答案:

I've found similar for answers on this topic:

  • Can I set variable column widths in pandas?
    will truncate column widths, but will not affect the title and will not wrap the text
  • Pretty printing newlines inside a string in a Pandas DataFrame
    This again touches on column contents but not the title

我正在使用Jupyter笔记本电脑,但如果可能的话,希望使用基于熊猫的解决方案.

I am working in a Jupyter notebook, but would prefer a pandas-based solution, if possible.

推荐答案

以下是不涉及更改IPython属性的答案:

Here is an answer that does not involve changing the IPython properties:

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')])])

这篇关于在Python Pandas DataFrame或Jupyter Notebook中包装列名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆