Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete the last two rows of a df with pandas [duplicate]

Here is the code I'm playing with. I want to delete the last two lines of the file. I'm actually working on a bigger file and the last two lines fluctuate. Once I get it to work on this small format, I will implement it in my primary source code.

import pandas as pd
data = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'], 
    'year': [2012, 2012, 2013, 2014, 2014], 
    'reports': [4, 24, 31, 2, 3]}
df = pd.DataFrame(data, index = ['Cochice', 'Pima', 'Santa Cruz', 
'Maricopa', 'Yuma'])
df
df.drop(dr.index[-2])

This will remove the second row from the bottom but I am trying to delete to rows that will be followed by NaN

like image 557
Roberto Gonzalez Avatar asked Dec 04 '18 16:12

Roberto Gonzalez


3 Answers

Beter is select all rows without last 2 by iloc:

df = df.iloc[:-2]
print (df)
             name  year  reports
Cochice     Jason  2012        4
Pima        Molly  2012       24
Santa Cruz   Tina  2013       31
like image 166
jezrael Avatar answered Oct 21 '22 01:10

jezrael


You can use df.tail to achieve that too -

df.drop(df.tail(n).index,inplace=True)
like image 28
jar Avatar answered Oct 21 '22 00:10

jar


You can try like this way to remove last 2 rows?

df = df[:-2]

Output:

After removing last 2 rows

            name   year  reports
Cochice     Jason  2012        4
Pima        Molly  2012       24
Santa Cruz   Tina  2013       31

Working Demo: https://repl.it/repls/UnacceptableWrithingQuotes

like image 36
Always Sunny Avatar answered Oct 21 '22 02:10

Always Sunny