+3 votes
in Programming Languages by (40.5k points)
I want to select the last N rows of a dataframe without sorting it. What function should I use for this?

1 Answer

+1 vote
by (347k points)
selected by
 
Best answer

The tail() function returns the last N rows from a Pandas DataFrame based on position. You can pass argument n=N to select N rows.

>>> import pandas as pd
>>> df = pd.DataFrame({'A':[10,20,30,40,50,60], 'B':[11,22,33,44,55,66], 'C':[12,24,36,48,60,72]})
>>> df
    A   B   C
0  10  11  12
1  20  22  24
2  30  33  36
3  40  44  48
4  50  55  60
5  60  66  72
>>> df.tail(3)
    A   B   C
3  40  44  48
4  50  55  60
5  60  66  72
>>> df.tail(n=3)
    A   B   C
3  40  44  48
4  50  55  60
5  60  66  72


...