[英]Why does jupyter sometimes print a DataFrame formatted and sometimes as text?
I have the following code in a jupypter notebook:我在 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'])
It prints the following:它打印以下内容:
Why is the second statement formatted tabularly (without a print
statement) whereas the first one is just text data?为什么第二个语句是表格格式(没有print
语句),而第一个只是文本数据? Is there a way to force print-format the DataFrame
with the nicely-formatted table applied?有没有办法强制打印格式DataFrame
并应用格式良好的表格?
test_csv.drop(columns=['platform'])
does not actually drop the column. test_csv.drop(columns=['platform'])
实际上并没有删除该列。 It just shows you the interim picture of dataframe by printing its state.它只是通过打印 state 向您展示 dataframe 的临时图片。
To actually drop the column:要实际删除列:
test_csv.drop(columns=['platform'], inplace=True)
OR或者
test_csv.drop('platform', axis=1, inplace=True)
test_csv['aggregator'] = None
changes the state of the dataframe by assigning a new column to it. test_csv['aggregator'] = None
通过为其分配一个新列来更改 dataframe 的 state。 Hence, it does not print anything.因此,它不打印任何东西。
Why does jupyter sometimes print a DataFrame formatted and sometimes as text?为什么 jupyter 有时会打印格式化的 DataFrame,有时会打印为文本?
if you use the function - print
it will print it as text because print is using the function to_string for any object it gets.如果您使用 function - print
它会将其打印为文本,因为 print 正在使用 function to_string 来处理它获得的任何 object。
and when you "leave" the data frame at the and of the cell it will show it as a table because it one of the functions that Jupiter does.当您将数据框“留在”单元格的 和 时,它会将其显示为表格,因为它是 Jupiter 的功能之一。
the function test_csv.drop(columns=['platform'])
returns df if you want it to do the drop in the dataFrame you have to use inplace=True
or df=df.drop(col)...
and than print the dataFrame function test_csv.drop(columns=['platform'])
返回 df 如果你希望它在 dataFrame 中下降,你必须使用 inplace inplace=True
或df=df.drop(col)...
然后打印dataFrame
I think you are running both the statements in the same cell of the Jupyter Notebook我认为您正在 Jupyter Notebook 的同一个单元格中运行这两个语句
You can run the below snippet in one cell您可以在一个单元格中运行以下代码段
# (1) How to add a new column?
test_csv['aggregator'] = None
test_csv # no need to use print
and in the other cell在另一个单元格中
# (2) How to remove a column?
test_csv.drop(columns=['platform'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.