我经常在终端上使用Series和DataFrames。Series的默认__repr__返回一个减少的样本,其中有一些头部和尾部值,但其余的都没有。
是否有一种内置的方式来漂亮地打印整个系列/数据帧?理想情况下,它应该支持适当的对齐,可能是列之间的边界,甚至可能是不同列的颜色编码。
我经常在终端上使用Series和DataFrames。Series的默认__repr__返回一个减少的样本,其中有一些头部和尾部值,但其余的都没有。
是否有一种内置的方式来漂亮地打印整个系列/数据帧?理想情况下,它应该支持适当的对齐,可能是列之间的边界,甚至可能是不同列的颜色编码。
当前回答
使用表格包:
pip install tabulate
考虑下面的示例用法:
import pandas as pd
from io import StringIO
from tabulate import tabulate
c = """Chromosome Start End
chr1 3 6
chr1 5 7
chr1 8 9"""
df = pd.read_table(StringIO(c), sep="\s+", header=0)
print(tabulate(df, headers='keys', tablefmt='psql'))
+----+--------------+---------+-------+
| | Chromosome | Start | End |
|----+--------------+---------+-------|
| 0 | chr1 | 3 | 6 |
| 1 | chr1 | 5 | 7 |
| 2 | chr1 | 8 | 9 |
+----+--------------+---------+-------+
其他回答
尝试使用display()函数。这将自动使用水平和垂直滚动条,这样你就可以轻松地显示不同的数据集,而不是使用print()。
display(dataframe)
Display()也支持正确的对齐。
然而,如果你想让数据集更漂亮,你可以检查pd.option_context()。它有很多选项来清楚地显示数据框架。
注:我正在使用Jupyter笔记本电脑。
使用表格包:
pip install tabulate
考虑下面的示例用法:
import pandas as pd
from io import StringIO
from tabulate import tabulate
c = """Chromosome Start End
chr1 3 6
chr1 5 7
chr1 8 9"""
df = pd.read_table(StringIO(c), sep="\s+", header=0)
print(tabulate(df, headers='keys', tablefmt='psql'))
+----+--------------+---------+-------+
| | Chromosome | Start | End |
|----+--------------+---------+-------|
| 0 | chr1 | 3 | 6 |
| 1 | chr1 | 5 | 7 |
| 2 | chr1 | 8 | 9 |
+----+--------------+---------+-------+
试试这个
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)
导入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')
你可以将expand_frame_repr设置为False:
显示。Expand_frame_repr:布尔值 是否打印宽DataFrame的完整DataFrame repr 跨多行,max_columns仍然得到尊重,但是输出 如果它的宽度超过了,会在多个“页面”上环绕吗 display.width。 (默认值:真实)
pd.set_option('expand_frame_repr', False)
要了解更多细节,请阅读如何漂亮地打印熊猫数据框架和系列