在 Python Pandas DataFrame 或 Jupyter Notebooks 中包装列名 [英] 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:
pd.DataFrame(np.random.randn(2, 10),
columns=['Very Long Column Title ' + str(i) for i in range(10)])
但是如果我有更少的列,标题将不会换行:
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)])
我也尝试过手动插入换行符:
I have also tried to manually insert a newline:
import pandas as pd
pd.DataFrame(np.random.randn(10, 2),
columns=['Very Long
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:
- 我可以在 Pandas 中设置可变列宽吗?
将截断列宽,但不会影响标题,也不会包裹文本 - 在 Pandas 的字符串内漂亮地打印换行符数据帧
这再次涉及列内容而不是标题
我正在使用 Jupyter 笔记本,但如果可能的话,我更喜欢基于 Pandas 的解决方案.
I am working in a Jupyter notebook, but would prefer a pandas-based solution, if possible.
推荐答案
这是一个不涉及更改 IPython 属性的答案:
Here is an answer that does not involve changing the IPython properties:
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')])])
这篇关于在 Python Pandas DataFrame 或 Jupyter Notebooks 中包装列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!