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

3

6

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

Alasteir answered 4/12, 2018 at 16:18 Comment(0)
W
14

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
Weirdie answered 4/12, 2018 at 16:19 Comment(0)
P
9

You can use df.tail to achieve that too -

df.drop(df.tail(n).index,inplace=True)
Pleven answered 4/12, 2018 at 16:21 Comment(0)
Q
4

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

Quadrumanous answered 4/12, 2018 at 16:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.