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
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
You can use df.tail
to achieve that too -
df.drop(df.tail(n).index,inplace=True)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With