在VS Code中漂亮地打印一个Pandas数据帧

40

我想知道在VS Code中是否可以像在PyCharm中显示Pandas数据框(第二张图片)一样显示数据框(第一张图片)?

感谢任何帮助。


df 在 VS Code 中的输出:

df print in vs code

df 在 PyCharm 中的输出:

df print in pycharm

5个回答

48

截至2021年1月发布版的Python扩展中,现在可以在调试本地Python程序时使用内置数据查看器查看Pandas数据框。当程序在断点处停止时,在变量列表中右键单击数据框变量,然后选择“在数据查看器中查看值”。

DataViewerWhenDebugging


4
我想知道为什么这个功能只在“变量”中可用,而不在“监视”中。有时使用“监视”更加方便,例如当有太多本地变量时,您需要检索您要找的变量。但是无论如何这是很棒的改进。 - Nicolas Dufaur
4
最后,我可以看到我的数据框了! - Sean McCarthy
2
请注意,您需要安装“jupyter”扩展程序,否则该选项将不可用。 - Nicolas Dufaur
这里有一个危险:数据查看器会将小值(低于1e10,看起来是这样)四舍五入为0。直接打印数据框将按预期显示它们。 - Eternal Ambiguity
如何显示带有“VARIABLES”的左侧面板? - Julien
1
当我在查看器中右键单击数据框时,我没有看到“在数据查看器中查看值”选项。 - glmorous

13

Tabulate是一个优秀的库,可以实现pandas df的漂亮打印:

信息 - 链接:[https://pypi.org/project/tabulate/]

请按照以下步骤完成漂亮的打印: (注意:为了简单说明,我将在Python中创建简单的数据帧)

1)安装tabulate

pip install --upgrade tabulate

这条语句将始终安装 tabulate 库的最新版本。

2)导入语句

import pandas as pd
from tabulate import tabulate

3) 创建简单的临时数据框

temp_data = {'Name': ['Sean', 'Ana', 'KK', 'Kelly', 'Amanda'], 
        'Age': [42, 52, 36, 24, 73], 
        'Maths_Score': [67, 43, 65, 78, 97],
        'English_Score': [78, 98, 45, 67, 64]}
df = pd.DataFrame(temp_data, columns = ['Name', 'Age', 'Maths_Score', 'English_Score'])

4) 没有对数据框进行制表,我们的打印输出将是:

print(df)

    Name  Age  Maths_Score  English_Score
0    Sean   42           67             78
1     Ana   52           43             98
2      KK   36           65             45
3   Kelly   24           78             67
4  Amanda   73           97             64

5) 使用tabulate之后,您的漂亮打印输出将是:

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

+----+--------+-------+---------------+-----------------+
|    | Name   |   Age |   Maths_Score |   English_Score |
|----+--------+-------+---------------+-----------------|
|  0 | Sean   |    42 |            67 |              78 |
|  1 | Ana    |    52 |            43 |              98 |
|  2 | KK     |    36 |            65 |              45 |
|  3 | Kelly  |    24 |            78 |              67 |
|  4 | Amanda |    73 |            97 |              64 |
+----+--------+-------+---------------+-----------------+

印刷效果清晰,感受爽脆!如果你喜欢我的回答,请留下评论!


嘿,谢谢你的回答,但我猜想人们正在寻找像这样的东西 - https://github.com/microsoft/vscode/issues/111105 - Yashash Gaurav
Tabulate 在 VS Code 中对我的大型 DataFrame 的工作非常出色! - Sean McCarthy
很好的回答,正确的链接是:https://pypi.org/project/tabulate/(你的链接末尾有一个“]”) - PeJota

3
除了@Shantanu的答案之外,Panda的to_markdown函数需要在Python中安装tabulate库,为表格提供各种纯文本格式,这些格式在VS Code编辑器中显示,例如:
df = pd.DataFrame(data={"animal_1": ["elk", "pig"], "animal_2": ["dog", "quetzal"]})
print(df.to_markdown())

|    | animal_1   | animal_2   |
|---:|:-----------|:-----------|
|  0 | elk        | dog        |
|  1 | pig        | quetzal    |

2

1

我没有在VS Code中找到类似的功能。如果您需要此功能,可以考虑使用Spyder IDE。Spyder IDE主页


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接