在 Python Pandas DataFrame 或 Jupyter Notebooks 中包装列名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43092345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:17:56  来源:igfitidea点击:

Wrapping column names in Python Pandas DataFrame or Jupyter Notebooks

pythonpandasdataframeformattingjupyter-notebook

提问by Rachel

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:

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

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

DataFrame with wrapped column names

带有包装列名称的 DataFrame

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 does not wrap column names

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:

我在这个主题上找到了类似的答案:

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

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

采纳答案by AndreyF

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

这是一个不涉及更改 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')])])

回答by James

Jupyter notebooks inherit their display properties from a number of sources. There is no property in pandasthat restricts the width of the column headers because pandasis not what causes the text to wrap, it is actually the rendered HTML.

Jupyter 笔记本从许多来源继承了它们的显示属性。没有pandas限制列标题宽度的属性,因为pandas这不是导致文本换行的原因,它实际上是呈现的 HTML。

You can overwrite the default Jupyter Notebook styles to restrict the maximum width of the table headers using:

您可以使用以下方法覆盖默认的 Jupyter Notebook 样式以限制表格标题的最大宽度:

from IPython.core.display import HTML
HTML("<style>.rendered_html th {max-width: 120px;}</style>")

Run this code once at the top of your notebook to set the max column width of html table headers to 120 pixels.

在笔记本顶部运行此代码一次,将 html 表标题的最大列宽设置为 120 像素。

回答by Yaakov Bressler

Alternatively, you could use the package textwrap:

或者,您可以使用包textwrap

import textwrap

cols = ['Very Long Column Title ' + str(i) for i in range(2)]

# Split wide columns, you can then join these with any delimiter you'd like
cols = [textwrap.wrap(x, width=20) for x in cols]

# print(cols)
# [['Very Long Column', 'Title 0'], ['Very Long Column', 'Title 1']]

回答by Roko Mijic

You can "hack in" the correct behavior by inserting spaces into column headings with:

您可以通过在列标题中插入空格来“入侵”正确的行为:

def colfix(df, L=5): return df.rename(columns=lambda x: ' '.join(x.replace('_', ' ')[i:i+L] for i in range(0,len(x),L)) if df[x].dtype in ['float64','int64'] else x )

colfix(your_df)

See my answer to a similar question https://stackoverflow.com/a/45078833/6903458

请参阅我对类似问题的回答https://stackoverflow.com/a/45078833/6903458