Delete the first three rows of a dataframe in pandas

PythonPandas

Python Problem Overview


I need to delete the first three rows of a dataframe in pandas.

I know df.ix[:-1] would remove the last row, but I can't figure out how to remove first n rows.

Python Solutions


Solution 1 - Python

Use iloc:

df = df.iloc[3:]

will give you a new df without the first three rows.

Solution 2 - Python

I think a more explicit way of doing this is to use drop.

The syntax is:

df.drop(label)

And as pointed out by @tim and @ChaimG, this can be done in-place:

df.drop(label, inplace=True)

One way of implementing this could be:

df.drop(df.index[:3], inplace=True)

And another "in place" use:

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

Solution 3 - Python

df = df.iloc[n:]

n drops the first n rows.

Solution 4 - Python

A simple way is to use tail(-n) to remove the first n rows

df=df.tail(-3)

Solution 5 - Python

df.drop(df.index[[0,2]])

Pandas uses zero based numbering, so 0 is the first row, 1 is the second row and 2 is the third row.

Solution 6 - Python

You can use python slicing, but note it's not in-place.

In [15]: import pandas as pd
In [16]: import numpy as np
In [17]: df = pd.DataFrame(np.random.random((5,2)))
In [18]: df
Out[18]:
          0         1
0  0.294077  0.229471
1  0.949007  0.790340
2  0.039961  0.720277
3  0.401468  0.803777
4  0.539951  0.763267

In [19]: df[3:]
Out[19]:
          0         1
3  0.401468  0.803777
4  0.539951  0.763267

Solution 7 - Python

inp0= pd.read_csv("bank_marketing_updated_v1.csv",skiprows=2)

or if you want to do in existing dataframe

simply do following command

Solution 8 - Python

There is a simple way to implement that by the drop command.

df = df.drop(3)

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
QuestionNilani AlgiriyageView Question on Stackoverflow
Solution 1 - PythonbdiamanteView Answer on Stackoverflow
Solution 2 - PythonC MarsView Answer on Stackoverflow
Solution 3 - Python176codingView Answer on Stackoverflow
Solution 4 - PythonmxiaView Answer on Stackoverflow
Solution 5 - PythonAnupam khareView Answer on Stackoverflow
Solution 6 - PythonbeardcView Answer on Stackoverflow
Solution 7 - PythonRahul kuchhadiaView Answer on Stackoverflow
Solution 8 - PythonAman BabbarView Answer on Stackoverflow