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

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

问题描述

我的数据框中某些列的标题很长,我希望能够将文本换行.我知道这个功能内置在熊猫中,就像我一样:

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 
 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:

我正在使用 Jupyter 笔记本,但如果可能的话,我更喜欢基于 Pandas 的解决方案.

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 Notebooks 中包装列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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