How to select second last row of a pandas dataframe using iloc[]?

Viewed 8301

I fetch the data from online and store that data in a pandas dataframe. But the problem is the dataframe format is not same every time mainly numbers of rows.

Print(df.shape)
Output: (100, 9)

--

Print(df.shape)
Output: (33, 9)

--

Print(df.shape)
Output: (153, 9)

--

Print(df.shape)
Output: (148, 9)

Can you please tell me how we can select only second last row or second last row’s any specific cell using iloc[]

3 Answers

df.iloc[-2] will get you the penultimate row info for all columns.

If you want a specific column only, df.loc doesn't like the minus sign, so one way you could do it would be: df.loc[(df.shape[0]-2), 'your_column_name']

Where df.shape[0] gets your row count, and -2 removes 2 from it to give you the index number for your penultimate row. Then you give it the required column name to only return that value.

You can get the second row from the back using index -2.

import pandas as pd
import numpy as np

a = np.matrix('1 2; 3 4; 5 6')
p = pd.DataFrame(a)
print("dataframe\n" + str(p))

print("second last row\n" + str(np.array(p.iloc[-2])))

Output:

dataframe
   0  1
0  1  2
1  3  4
2  5  6

second last row
[3 4]

You can also use take:

# all columns
df.take([-2])

# specific column
df['foo'].take([-2])
Related