python - 为什么 jupyter 有时打印格式化的 DataFrame 有时打印为文本?

标签 python pandas dataframe jupyter-notebook google-colaboratory

我在 jupypter notebook 中有以下代码:

# (1) How to add a new column?
test_csv['aggregator'] = None
print (test_csv)

# (2) How to remove a column?
test_csv.drop(columns=['platform'])

打印如下:

enter image description here

为什么第二个语句是表格格式的(没有 print 语句)而第一个只是文本数据?有没有一种方法可以强制打印格式化 DataFrame 并应用格式良好的表格?

最佳答案

Ran Cohen 已经提到打印函数的“为什么”部分破坏了漂亮的格式。

要获得格式良好(灰色和白色的表格格式)数据框,您可以将其留在单元格的末尾,但这仅适用于单个数据框。 如果想要打印多个格式良好的数据帧,可以使用

1)

from IPython.display import display
display(df1) #displays nicely formatted dataframe1
display(df2) #displays nicely formatted dataframe2

2)

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
df1
df2
#displays both dataframes, nicely formatted

注意:Jupyter notebook 呈现(样式化和显示)数据框的 HTML 版本是很好的格式,与浏览器呈现 html 代码的方式相同。(这里虽然真正的 HTML 代码是从 df1.to_html( ) 当由浏览器呈现时,表的较少风格作为独立的 html 代码,因为 Jupyter Notebook 添加了一些额外的样式)

来源:

  1. Stackoverflow Article, same question,my answer attributed to the ones given there

  2. Found Solution Here First

  3. Stackoverflow Article, related to rendering

关于python - 为什么 jupyter 有时打印格式化的 DataFrame 有时打印为文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63430328/

相关文章:

python - 如何使用 pygtk 在窗口中包含图像?

python - 如何使用 Socks5 代理抓取请求?

Python Pandas 系列元组数据框

python - 数据框的分组依据和列的平均值

python - 错误 : object of type 'zip' has no len() after adding extra header by using zip

python - 具有替换和最大出现约束的组合

python - 使用列表和切片

python - 从列中的字符串中删除不需要的部分

python - 比较一行中的值并将结果写入新列

dataframe - 如何使用 julia 将数据框的列乘以日志?