pandas 如何删除数据框中的所有行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24612584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:13:53  来源:igfitidea点击:

How to delete all rows in a dataframe?

pythonpandas

提问by cammil

I want to delete allthe rows in a dataframe.

我想删除数据框中的所有行。

The reason I want to do this is so that I can reconstruct the dataframe with an iterative loop. I want to start with a completely empty dataframe.

我想这样做的原因是我可以用迭代循环重建数据帧。我想从一个完全空的数据框开始。

Alternatively, I could create an empty df from just the column / type information if that is possible

或者,如果可能的话,我可以仅从列/类型信息创建一个空的 df

采纳答案by FooBar

The latter is possible and strongly recommended - "inserting" rows row-by-row is highly inefficient. A sketch could be

后者是可能的并且强烈推荐 - 逐行“插入”行效率非常低。草图可以是

>>> import numpy as np
>>> import pandas as pd
>>> index = np.arange(0, 10)
>>> df = pd.DataFrame(index=index, columns=['foo', 'bar'])
>>> df
Out[268]: 
   foo  bar
0  NaN  NaN
1  NaN  NaN
2  NaN  NaN
3  NaN  NaN
4  NaN  NaN
5  NaN  NaN
6  NaN  NaN
7  NaN  NaN
8  NaN  NaN
9  NaN  NaN

回答by ashishsingal

Here's another method if you have an existing DataFrame that you'd like to empty without recreating the column information:

如果您有一个现有的 DataFrame 想要清空而不重新创建列信息,那么这是另一种方法:

df_empty = df[0:0]

df_emptyis a DataFrame with zero rows but with the same column structure as df

df_empty是一个具有零行但具有相同列结构的 DataFrame df