我经常在终端上使用Series和DataFrames。Series的默认__repr__返回一个减少的样本,其中有一些头部和尾部值,但其余的都没有。

是否有一种内置的方式来漂亮地打印整个系列/数据帧?理想情况下,它应该支持适当的对齐,可能是列之间的边界,甚至可能是不同列的颜色编码。


当前回答

脚本

没有人提出过这种简单的纯文本解决方案:

from pprint import pprint

pprint(s.to_dict())

产生如下结果:

{'% Diabetes': 0.06365372374283895,
 '% Obesity': 0.06365372374283895,
 '% Bachelors': 0.0,
 '% Poverty': 0.09548058561425843,
 '% Driving Deaths': 1.1775938892425206,
 '% Excessive Drinking': 0.06365372374283895}

Jupyter記本嗎

此外,当使用Jupyter笔记本时,这是一个很好的解决方案。

注意:pd.Series()没有.to_html(),所以必须转换为pd.DataFrame()

from IPython.display import display, HTML

display(HTML(s.to_frame().to_html()))

产生如下结果:

其他回答

导入pandas后,作为使用上下文管理器的另一种选择,设置这些选项来显示整个数据框架:

pd.set_option('display.max_columns', None)  # or 1000
pd.set_option('display.max_rows', None)  # or 1000
pd.set_option('display.max_colwidth', None)  # or 199

有关有用选项的完整列表,请参见:

pd.describe_option('display')

如果您正在使用Ipython Notebook (Jupyter)。你可以使用HTML

from IPython.core.display import HTML
display(HTML(df.to_html()))

你也可以使用带有一个或多个选项的option_context:

with pd.option_context('display.max_rows', None, 'display.max_columns', None):  # more options can be specified also
    print(df)

这将自动将选项返回到它们以前的值。

如果你在jupyter-notebook上工作,使用display(df)而不是print(df)将使用jupyter丰富的显示逻辑(就像这样)。

尝试使用display()函数。这将自动使用水平和垂直滚动条,这样你就可以轻松地显示不同的数据集,而不是使用print()。

display(dataframe)

Display()也支持正确的对齐。

然而,如果你想让数据集更漂亮,你可以检查pd.option_context()。它有很多选项来清楚地显示数据框架。

注:我正在使用Jupyter笔记本电脑。

试试这个

pd.set_option('display.height',1000)
pd.set_option('display.max_rows',500)
pd.set_option('display.max_columns',500)
pd.set_option('display.width',1000)