Alister jordan
Alister jordan

Reputation: 99

how to get last n indices in a python dataframe?

i have the following dataframe:

        volume
index
 1        65
 1        55
 2        44
 2        56
 3        46
 3        75
 4        64
 4        64

when i put the code df.iloc[-2:] .it only shows the last two rows of my dataframe. example:

        volume
index
 4        64
 4        64

i want to get the last two indices with the result below

        volume
index
 3        46
 3        75
 4        64
 4        64

how do i go about it?

Upvotes: 2

Views: 538

Answers (1)

Erfan
Erfan

Reputation: 42906

You can slice the index after getting the unique values, then use Series.isin:

df[df.index.isin(df.index.unique()[-2:])]

Or

df.loc[df.index.unique()[-2:]]
       volume
index        
3          46
3          75
4          64
4          64

Upvotes: 5

Related Questions