Drop all data in a pandas dataframe

PythonPython 2.7Pandas

Python Problem Overview


I would like to drop all data in a pandas dataframe, but am getting TypeError: drop() takes at least 2 arguments (3 given). I essentially want a blank dataframe with just my columns headers.

import pandas as pd

web_stats = {'Day': [1, 2, 3, 4, 2, 6],
             'Visitors': [43, 43, 34, 23, 43, 23],
             'Bounce_Rate': [3, 2, 4, 3, 5, 5]}
df = pd.DataFrame(web_stats)

df.drop(axis=0, inplace=True)
print df

Python Solutions


Solution 1 - Python

You need to pass the labels to be dropped.

df.drop(df.index, inplace=True)

By default, it operates on axis=0.

You can achieve the same with

df.iloc[0:0]

which is much more efficient.

Solution 2 - Python

My favorite:

df = df.iloc[0:0]

But be aware df.index.max() will be nan. To add items I use:

df.loc[0 if math.isnan(df.index.max()) else df.index.max() + 1] = data

Solution 3 - Python

My favorite way is:

df = df[0:0] 

Solution 4 - Python

Overwrite the dataframe with something like that

import pandas as pd

df = pd.DataFrame(None)

or if you want to keep columns in place

df = pd.DataFrame(columns=df.columns)

Solution 5 - Python

If your goal is to drop the dataframe, then you need to pass all columns. For me: the best way is to pass a list comprehension to the columns kwarg. This will then work regardless of the different columns in a df.

import pandas as pd

web_stats = {'Day': [1, 2, 3, 4, 2, 6],
             'Visitors': [43, 43, 34, 23, 43, 23],
             'Bounce_Rate': [3, 2, 4, 3, 5, 5]}
df = pd.DataFrame(web_stats)

df.drop(columns=[i for i in check_df.columns])

Solution 6 - Python

This code make clean dataframe:

df = pd.DataFrame({'a':[1,2], 'b':[3,4]})
#clean
df = pd.DataFrame()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2242044View Question on Stackoverflow
Solution 1 - PythonayhanView Answer on Stackoverflow
Solution 2 - PythontomatomView Answer on Stackoverflow
Solution 3 - PythonRaul MenendezView Answer on Stackoverflow
Solution 4 - PythonZisis FView Answer on Stackoverflow
Solution 5 - PythonMattView Answer on Stackoverflow
Solution 6 - PythonSergey SvetloffView Answer on Stackoverflow