+1 vote
in Programming Languages by (66.2k points)
The last row of a Pandas dataframe contains some NaN values. Therefore, I want to delete the last row. How can I delete it and keep the rest of the rows?

1 Answer

+2 votes
by (281k points)
 
Best answer

You can use either iloc or drop() method to delete the last row of a dataframe. You need to provide the index of the last row to the drop() method. To use iloc, you need to provide the index of the first row to the second last row.

Here is an example:

>>> import pandas as pd
>>> df=pd.DataFrame({'a1':[1,2,3,4,5], 'b1':[11,12,13,14,15]})
>>> df
   a1  b1
0   1  11
1   2  12
2   3  13
3   4  14
4   5  15
>>> ndf=df.iloc[:df.shape[0] - 1, :]
>>> ndf
   a1  b1
0   1  11
1   2  12
2   3  13
3   4  14

>>> ndf=df.drop(index=len(df) - 1)
>>> ndf
   a1  b1
0   1  11
1   2  12
2   3  13
3   4  14

If you want to modify the original dataframe directly without creating a new one, you can use the inplace=True parameter: 

>>> df.drop(index=len(df) - 1, inplace=True)
>>> df
   a1  b1
0   1  11
1   2  12
2   3  13
3   4  14
>>>


...