简体   繁体   English

在 Python Pandas DataFrame 或 Jupyter 笔记本中包装列名

[英]Wrapping column names in Python Pandas DataFrame or 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:我知道这个功能内置于 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.但这给出了与上面相同的 output。

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 notebook 上工作,但如果可能的话,我更喜欢基于 pandas 的解决方案。

Jupyter notebooks inherit their display properties from a number of sources. Jupyter笔记本从许多来源继承了它们的显示属性。 There is no property in pandas that restricts the width of the column headers because pandas is not what causes the text to wrap, it is actually the rendered HTML. 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像素。

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

Alternatively, you could use the package textwrap :或者,您可以使用 package 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']]

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

A version of @AndreyF's answer that works regardless of whether you are using Jupyter.无论您是否使用 Jupyter,@AndreyF 的答案版本都有效。 The routine uses the Pandas styler to render the dataframe as HTML. To view the table then, you must save the HTML to file and open it in a browser.该例程使用 Pandas 样式器将 dataframe 呈现为 HTML。然后要查看表格,您必须将 HTML 保存到文件并在浏览器中打开它。 Notice that the styler is caught explicitly as a variable.请注意,样式器被显式捕获为变量。

df = pd.DataFrame(np.random.randn(10, 2), 
    columns=['Very Long Column Title ' + str(i) for i in range(2)])
styler = df.style.set_table_styles([dict(selector="th",props=[('max-width', '50px')])])
with open("/tmp/testStyle.html",'w') as f: f.write(styler.render())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Jupyter Notebooks 中使用 Python 更改列名 - Changing column name with Python in Jupyter Notebooks 带有列名称列表的Python Pandas索引数据框 - Python Pandas Indexing Dataframe with List of Column Names 在 python 中过滤具有特定列名的熊猫数据框 - Filter pandas dataframe with specific column names in python 包装熊猫数据框的列名 - Wrapping column name of pandas dataframe 当数据框列中的值为 x 时,使用 Jupyter Notebooks 和 Python 计算另一个列值为 y 的次数? - When a value in a dataframe's column is x, count how many times another columns value is y using Jupyter Notebooks & Python? 用“foldover”(包装)在jupyter笔记本中显示“长”pandas数据帧? - Display “long” pandas dataframe in jupyter notebook with “foldover” (wrapping)? Python / Pandas-使用年份列名称动态计算数据框中的年比率 - Python / Pandas - Dynamically calculate yearly ratios in a dataframe with year column names 重命名python pandas数据框的前n列名称后出现KeyError - KeyError after renaming the first n column names of python pandas dataframe Python 将列名添加到 Pandas DataFrame 时引发值错误 - Python raising Value Error when adding column names to Pandas DataFrame Python 3:获取与pandas dataframe某列中的值关联的索引名称 - Python 3: Get index names associated with the values in a certain column of pandas dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM