Delete the first three rows of the data frame in pandas

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

I know that df.ix[:-1] will delete the last line, but I cannot figure out how to delete the first n lines.

+70
pandas
May 6 '13 at 10:35
source share
5 answers

Use iloc as you used ix , but use a different slice ...

 df2 = df1.iloc[3:] #edited since .ix is now deprecated. 

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

+79
May 6 '13 at 12:04
source share

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

Syntax:

 df.drop(label) 

And as @tim and @ChaimG pointed out, this can be done locally:

 df.drop(label, inplace=True) 

One way to implement this could be:

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

And one more "in place":

 df.drop(df.head(3).index, inplace=True) 
+74
Jul 30 '13 at 14:39
source share

You can use python slicing, but note that this is 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 
+4
May 10 '13 at 17:25
source share
 df=df.iloc[n:] 

n is the first n lines

+2
May 16 '17 at 10:50
source share
 df.drop(df.index[[0,2]]) 

Pandas uses zero numbering, so 0 is the first line, 1 is the second line, and the second is the third line.

+1
Jul 19 '17 at 19:39
source share



All Articles