Python 我可以在 Pandas 中设置可变列宽吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39680147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:35:01  来源:igfitidea点击:

Can I set variable column widths in pandas?

pythonpandas

提问by scrollex

I've got several columns with long strings of text in a pandas data frame, but am only interested in examining one of them. Is there a way to use something along the lines of pd.set_option('max_colwidth', 60)but for a single columnonly, rather than expanding the width of all the columns in my df?

我在熊猫数据框中有几列带有长文本字符串的列,但我只对检查其中之一感兴趣。有没有办法只pd.set_option('max_colwidth', 60)单个列使用一些东西,而不是扩展我的 df 中所有列的宽度?

回答by Romain

If you want to change the display in a Jupyter Notebook, you can use the Stylefeature. To use this formatting for only some columns simply indicate the column(s) to enlarge thanks to the subsetparameter. This is basically HTML and CSS.

如果要更改 Jupyter Notebook 中的显示,可以使用样式功能。要仅对某些列使用此格式,只需通过subset参数指示要放大的列。这基本上是 HTML 和 CSS。

### Test data
df = DataFrame({'text': ['foo foo foo foo foo foo foo foo', 'bar bar bar bar bar'],
                 'number': [1, 2]})

df.style.set_properties(subset=['text'], **{'width': '300px'})

enter image description here

在此处输入图片说明

回答by Tom Bush

The easiest solution I have found on newer versions of Pandas is outlined in this pageof the Pandas reference materials. Search for display.max_colwidth-- about 1/3rd of the way down the page describes how to use it e.g.:

我在 Pandas 的新版本中找到的最简单的解决方案在 Pandas 参考资料的这个页面中进行了概述。搜索display.max_colwidth- 页面下方大约 1/3 处描述了如何使用它,例如:

pd.set_option('max_colwidth', 400)

pd.set_option('max_colwidth', 400)

Note that this well set the value for the session, or until changed.

请注意,这很好地设置了会话的值,或者直到更改为止。

If you only want to make temporary changes see this infoon temporarily setting context e.g.:

如果您只想进行临时更改,请参阅有关临时设置上下文的信息,例如:

from pandas import option_context

with option_context('display.max_colwidth', 400):
    display(df.head())

I've not found an obvious way to set individual columns but this approach only scales up those that need more space to the maximum you set.

我还没有找到设置单个列的明显方法,但这种方法只会将需要更多空间的那些扩展到您设置的最大值。

Also possibly of use if trying to adjust how to fit things on screen/in tables/making space for other columns is pd.set_option('precision', 2)which changes the no of decimal places.

如果尝试调整屏幕/表格中的内容/为其他列腾出空间的方式,也可能有用pd.set_option('precision', 2),这会改变小数位数。