【问题标题】:Rotating the column name for a Panda DataFrame旋转 Pandas DataFrame 的列名
【发布时间】:2018-03-24 18:04:21
【问题描述】:

我正在尝试使用 pandas 制作格式精美的表格。我的一些列名太长了。这些列的单元格很大,导致整个表格一团糟。

在我的示例中,是否可以在显示列名时旋转它们?

data = [{'Way too long of a column to be reasonable':4,'Four?':4},
        {'Way too long of a column to be reasonable':5,'Four?':5}]
pd.DataFrame(data)

【问题讨论】:

  • 可以加标签jupyter notebook
  • 显然这取决于您的情况,但也许只是缩短/改进列名是有意义的?但对于解决方法,您可以考虑转换为“假”多索引。例如。如果列名是“david s南瓜”,您可以将“david s”作为顶层,将“pumpkins”作为第二层。显然这不是多索引的用途,但我认为它基本上可以满足您的需求。
  • @JohnE,感谢您的建议。文本换行是@Wen 建议的,但已被删除:df.style.set_table_styles([dict(selector="th",props=[('max-width', '50px')])]) 这是一个很好的解决方法,适用于短语,就像在我的示例中一样。不过我也有长话。我仍然很好奇是否可以旋转!我不是 CSS 选择器专家,但我认为这应该可行,但不行:dfoo.style.set_table_styles([dict(selector="th",props=[('text-orientation', 'upright')])])
  • 我刚刚重新阅读了文档页面 (pandas.pydata.org/pandas-docs/version/0.19.2/style.html),其中指出 '您只能设置值的样式,而不是索引或列的样式',但文档显示正在格式化的列和索引。也许这才刚刚开始解决。

标签: python pandas dataframe jupyter-notebook


【解决方案1】:

类似:

data = [{'Way too long of a column to be reasonable':4,'Four?':4},
        {'Way too long of a column to be reasonable':5,'Four?':5}]
dfoo = pd.DataFrame(data)
dfoo.style.set_table_styles(
    [dict(selector="th",props=[('max-width', '80px')]),
        dict(selector="th.col_heading",
                 props=[("writing-mode", "vertical-rl"), 
                        ('transform', 'rotateZ(-90deg)'),
                        ])]
)

可能接近你想要的:

see result here

【讨论】:

  • 更改我接受的答案。这仅使用 Pandas 库完成任务,并将显示在 JupyterLab 中。干得好!
  • 我发现(在 Firefox 中)rotateZ(-90deg) 参数导致标题向后旋转,因此它们又是水平的。我使用('vertical-align', 'text-top'), ('transform', 'rotateZ(180deg)') 得到了一个更好的布局,它将文本沿表格的第一行对齐。
  • 在@Nate 的评论之后,正确旋转列名的设置是props=[('vertical-align', 'text-top'), ('transform', 'rotateZ(-90deg)')]
【解决方案2】:

查看pybloqs source code 以获取已接受答案的解决方案,我能够了解如何在不安装 pybloqs 的情况下旋转列。请注意,这也会旋转索引,但我添加了代码来删除它们。

from IPython.display import HTML, display

data = [{'Way too long of a column to be reasonable':4,'Four?':4},
        {'Way too long of a column to be reasonable':5,'Four?':5}]
df = pd.DataFrame(data)

styles = [
    dict(selector="th", props=[("font-size", "125%"),
                               ("text-align", "center"),
                              ("transform", "translate(0%,-30%) rotate(-5deg)")
                              ]),
    dict(selector=".row_heading, .blank", props= [('display', 'none;')])
]

html = df.style.set_table_styles(styles).render()
display(HTML(html))

【讨论】:

    【解决方案3】:

    使用 Python 库 'pybloqs' (http://pybloqs.readthedocs.io/en/latest/),可以旋转列名以及在顶部添加填充。唯一的缺点(如文档所述)是顶部填充不能与 Jupyter 内联。必须导出表。

    import pandas as pd
    from pybloqs import Block
    import pybloqs.block.table_formatters as tf
    from IPython.core.display import display, HTML
    
    data = [{'Way too long of a column to be reasonable':4,'Four?':4},
            {'Way too long of a column to be reasonable':5,'Four?':5}]
    dfoo =pd.DataFrame(data)
    
    fmt_header = tf.FmtHeader(fixed_width='5cm',index_width='10%', 
                              top_padding='10cm', rotate_deg=60)
    table_block = Block(dfoo, formatters=[fmt_header])
    
    display(HTML(table_block.render_html()))
    table_block.save('Table.html')
    

    【讨论】:

      【解决方案4】:

      我将@Bobain 的好答案放入一个函数中,这样我就可以在整个笔记本中重复使用它。

      def format_vertical_headers(df):
          """Display a dataframe with vertical column headers"""
          styles = [dict(selector="th", props=[('width', '40px')]),
                    dict(selector="th.col_heading",
                         props=[("writing-mode", "vertical-rl"),
                                ('transform', 'rotateZ(180deg)'), 
                                ('height', '290px'),
                                ('vertical-align', 'top')])]
          return (df.fillna('').style.set_table_styles(styles))
      
      format_vertical_headers(pandas.DataFrame(data))
      

      【讨论】:

      • 我没有得到相同的布局 - 文本是水平上下颠倒的。 .没有足够的空间来解释我在尝试不同参数方面取得的有限进展。也许添加另一条评论来解释它们? print(pd.__version__) 说我的熊猫版本是 1.2,1,而 jupyter 版本是 jupyter 核心:4.7.1 jupyter-notebook:6.4.3 qtconsole:未安装 ipython:7.26.0 ipykernel:6.1.0 jupyter 客户端:6.1。 12 jupyter 实验室:3.1.6 nbconvert:6.1.0 ipywidgets:未安装 nbformat:5.1.3 traitlets:5.0.5
      • 我找到的最好的 mod 在下面但仍然不是垂直的: def format_vertical_headers(df): """显示带有垂直列标题的数据框""" styles = [dict(selector="th" , props=[('width', '40px')]), dict(selector="th.col_heading", props=[("writing-mode", "vertical-rl"), ('transform', 'rotateZ (180deg)'), ('height', '290px'), ('vertical-align', 'top')])] 返回 (df.fillna('').style.set_table_styles(styles)) format_vertical_headers(pd .DataFrame(数据))
      • @Bill 请提出一个新问题并提供reproducible example
      【解决方案5】:

      我可以让文本完全旋转 90 度,但不知道如何使用 text-orientation: upright,因为它只会使文本不可见 :( 你错过了必须的 writing-mode 属性设置为text-orientation 以产生任何效果。另外,我通过稍微修改选择器使其仅适用于列标题。

      dfoo.style.set_table_styles([dict(selector="th.col_heading",props=[("writing-mode", "vertical-lr"),('text-orientation', 'upright')])])

      希望这能让你离目标更近一点!

      【讨论】:

      • 这肯定越来越暖和了!所有单个字母都至少旋转
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 2021-04-24
      • 2017-02-10
      • 2016-07-01
      相关资源
      最近更新 更多