2017-10-12 122 views
4

我想从熊猫做出很好的格式化表。我的一些列名太长了。这些列的单元格很大,导致整个表格变得混乱。旋转熊猫DataFrame的列名

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

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) 

I would like to rotate the names of the columns as displayed here.

+1

请你加标签'jupyter notebook' – Wen

+0

显然,这取决于你的情况,但也许是有意义的只是缩短/提高列名?但是,对于解决方法,您可以考虑转换为“假”多索引。例如。如果列名是“大卫南瓜”,你可以将“大卫”作为最高级别,将“南瓜”作为第二级别。显然,这并不是多指标的,但我认为它基本上会做你想做的。 – JohnE

+0

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

回答

1

使用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') 

Table in HTML with rotated column names

1

我能得到它,使文本完全转身90度,但无法弄清楚如何使用text-orientation: upright,因为它只是使文字无形:(你失踪了具有用于text-orientation被设置writing-mode属性有什么影响。另外,我把它只能通过修改选择一点适用于列标题。

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

希望这能让你更接近你的目标!

+0

这绝对会变暖!所有的单个字母至少旋转 –