繁体   English   中英

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

[英]Wrapping column names in Python Pandas DataFrame or Jupyter Notebooks

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

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

DataFrame 带有包装的列名

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

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

DataFrame 不换列名

我还尝试手动插入换行符:

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

但这给出了与上面相同的 output。

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

我在 Jupyter notebook 上工作,但如果可能的话,我更喜欢基于 pandas 的解决方案。

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

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

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

在笔记本顶部运行此代码一次,将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')])])

或者,您可以使用 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']]

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

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)

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

无论您是否使用 Jupyter,@AndreyF 的答案版本都有效。 该例程使用 Pandas 样式器将 dataframe 呈现为 HTML。然后要查看表格,您必须将 HTML 保存到文件并在浏览器中打开它。 请注意,样式器被显式捕获为变量。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM