我如何打印一个熊猫数据框架作为一个漂亮的基于文本的表,就像下面?

+------------+---------+-------------+
| column_one | col_two |   column_3  |
+------------+---------+-------------+
|          0 |  0.0001 | ABCD        |
|          1 |  1e-005 | ABCD        |
|          2 |  1e-006 | long string |
|          3 |  1e-007 | ABCD        |
+------------+---------+-------------+

当前回答

我刚刚找到了一个很好的工具来满足这种需求,它叫做表格。

它打印表格数据并使用DataFrame。

from tabulate import tabulate
import pandas as pd

df = pd.DataFrame({'col_two' : [0.0001, 1e-005 , 1e-006, 1e-007],
                   'column_3' : ['ABCD', 'ABCD', 'long string', 'ABCD']})

print(tabulate(df, headers='keys', tablefmt='psql'))

+----+-----------+-------------+
|    |   col_two | column_3    |
|----+-----------+-------------|
|  0 |    0.0001 | ABCD        |
|  1 |    1e-05  | ABCD        |
|  2 |    1e-06  | long string |
|  3 |    1e-07  | ABCD        |
+----+-----------+-------------+

注意:

要抑制所有类型数据的行索引,传递showindex="never"或showindex=False。

其他回答

熊猫>= 1.0

如果你想要一个内置的函数来转储你的数据到一些github markdown,你现在有一个。看看to_markdown:

df = pd.DataFrame({"A": [1, 2, 3], "B": [1, 2, 3]}, index=['a', 'a', 'b'])  
print(df.to_markdown()) 

|    |   A |   B |
|:---|----:|----:|
| a  |   1 |   1 |
| a  |   2 |   2 |
| b  |   3 |   3 |

这是它在github上的样子:

请注意,您仍然需要安装表格包。

我使用丰富的库,它有更好看的表比基于.to_markdown()。

import pandas as pd
from rich.console import Console
from rich.table import Table
df = pd.DataFrame({'col_two' : [0.0001, 1e-005 , 1e-006, 1e-007],
                   'column_3' : ['ABCD', 'ABCD', 'long string', 'ABCD']})
console = Console()
table = Table('Title')
table.add_row(df.to_string(float_format=lambda _: '{:.4f}'.format(_)))
console.print(table)

给你这个表格:

更多定制选项请参阅文档:

https://rich.readthedocs.io/en/stable/tables.html

更新:一个更好的解决方案是简单地把数据帧的变量名放在单元格的最后一行。它会自动打印出漂亮的格式。

import pandas as pd
import numpy as np

df = pd.DataFrame({'Data1': np.linspace(0,10,11), 'Data2': np.linspace(10,0,11)})
df

一个简单的方法是输出为html, pandas开箱即用:

df.to_html('temp.html')

我刚刚找到了一个很好的工具来满足这种需求,它叫做表格。

它打印表格数据并使用DataFrame。

from tabulate import tabulate
import pandas as pd

df = pd.DataFrame({'col_two' : [0.0001, 1e-005 , 1e-006, 1e-007],
                   'column_3' : ['ABCD', 'ABCD', 'long string', 'ABCD']})

print(tabulate(df, headers='keys', tablefmt='psql'))

+----+-----------+-------------+
|    |   col_two | column_3    |
|----+-----------+-------------|
|  0 |    0.0001 | ABCD        |
|  1 |    1e-05  | ABCD        |
|  2 |    1e-06  | long string |
|  3 |    1e-07  | ABCD        |
+----+-----------+-------------+

注意:

要抑制所有类型数据的行索引,传递showindex="never"或showindex=False。