Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete all rows in a dataframe?

Tags:

python

pandas

I want to delete all the 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

like image 284
cammil Avatar asked Jul 07 '14 14:07

cammil


People also ask

How delete all rows from DataFrame Pandas?

To remove rows in Pandas DataFrame, use the drop() method. The Pandas dataframe drop() is a built-in function that is used to drop the rows. The drop() removes the row based on an index provided to that function.

How do you delete all rows in Python?

By using dropna() method you can drop rows with NaN (Not a Number) and None values from pandas DataFrame. Note that by default it returns the copy of the DataFrame after removing rows. If you wanted to remove from the existing DataFrame, you should use inplace=True .

How do I delete 1000 rows in Pandas?

Use drop() to remove first N rows of pandas dataframe In pandas, the dataframe's drop() function accepts a sequence of row names that it needs to delete from the dataframe.


2 Answers

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

df_empty = df[0:0] 

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

like image 93
ashishsingal Avatar answered Sep 21 '22 16:09

ashishsingal


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 
like image 42
FooBar Avatar answered Sep 20 '22 16:09

FooBar