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

问题描述

我在jupypter笔记本中有以下代码

# (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的格式?

解决方法

test_csv.drop(columns=['platform'])实际上并不删除该列。它只是通过打印数据帧的状态为您显示数据帧的临时图片。

要实际删除该列:

test_csv.drop(columns=['platform'],inplace=True)

OR

test_csv.drop('platform',axis=1,inplace=True)

test_csv['aggregator'] = None通过为数据框分配新列来更改其状态。因此,它不会打印任何内容。

,

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

如果您使用函数-print,它将打印为文本,因为print对其获取的任何对象都使用函数to_string。

当您在单元格的和处“离开”数据帧时,它将显示为表格,因为它是Jupiter的功能之一。

enter image description here

函数test_csv.drop(columns=['platform'])返回df 如果您希望它执行dataFrame中的删除操作,则必须使用inplace=Truedf=df.drop(col)... 然后打印dataFrame

,

我认为您正在Jupyter Notebook的同一单元中运行这两个语句

您可以在一个单元格中运行以下代码段

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

以及其他单元格

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